Snippets Collections
import { fetchBaseQuery } from '@reduxjs/toolkit/query'
import { tokenReceived, loggedOut } from './authSlice'

const baseQuery = fetchBaseQuery({ baseUrl: '/' })
const baseQueryWithReauth = async (args, api, extraOptions) => {
  let result = await baseQuery(args, api, extraOptions)
  if (result.error && result.error.status === 401) {
    // try to get a new token
    const refreshResult = await baseQuery('/refreshToken', api, extraOptions)
    if (refreshResult.data) {
      // store the new token
      api.dispatch(tokenReceived(refreshResult.data))
      // retry the initial query
      result = await baseQuery(args, api, extraOptions)
    } else {
      api.dispatch(loggedOut())
    }
  }
  return result
}
star

Sat Jun 24 2023 15:46:54 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/72613859/refresh-token-with-redux-toolkit-query

#javascript #redux #rtk

Save snippets that work with our extensions

Available in the Chrome Web Store Get Firefox Add-on Get VS Code extension