When API calls in React RTK query endpoints and receive response, but some times if the server throws an error, and API returns error – how to handle this in Axios its provide interceptor.
Can we implement interceptor in Redux RTK query or are there other alternatives to handle errors?
2
Answers
Here’s an example how I have used axios interceptors with Redux-Toolkit Query with an axios base query function.
In the above example the code is simply looking for 401/403 error response status codes to log the user out, but you can run any business logic necessary for your specific use case in the error handler.
Generally, you should not reach for Axios (your browser already ships with fetch, and axios doesn’t add a ton of functionality, but it does add a good bunch of bundle size – it’s only really necessary if you target very legacy platforms), but stay with the normal
fetchBaseQuery
. Instead of doing interceptors, you would just "wrap" a new function around the function created byfetchBaseQuery
.The concept of "interceptors" is really overblown if you also just can wrap your baseQuery instead.