Home > Back-end >  How to make a response interceptor in RTK Query
How to make a response interceptor in RTK Query

Time:07-24

I need to redirect to log in screen and clear the authentication token when the response status from an API is unauthorized.
I could do this in Angular easily by providing an HTTP interceptor to the module, so I'm looking for an equivalent in RTK Query in React.
Is there a way to add a global interceptor via RTK query? Or an interceptor for the response to a group of queries?
I thought of implementing the logic to do the above using the transformResponse field but doing it there doesn't seem right, and I'll have to add the function call to the body of every transformResponse callback.

CodePudding user response:

You do that by wrapping your fetchBaseQuery. There is an example that does this for re-authorization in the documentation:

Automatic re-authorization by extending fetchBaseQuery


const baseQuery = fetchBaseQuery({ baseUrl: '/' })
const baseQueryWithReauth: BaseQueryFn<
  string | FetchArgs,
  unknown,
  FetchBaseQueryError
> = async (args, api, extraOptions) => {
  let result = await baseQuery(args, api, extraOptions)
  if (result.error && result.error.status === 401) {
    // your logic here
  }
  return result
}
  • Related