Refresh token with Redux Toolkit Query - Stack Overflow

PHOTO EMBED

Sat Jun 24 2023 15:46:54 GMT+0000 (Coordinated Universal Time)

Saved by @snishant011 #javascript #redux #rtk

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
}
content_copyCOPY

https://stackoverflow.com/questions/72613859/refresh-token-with-redux-toolkit-query