RTK query — How to centralize error handling
When we receive errors from queries or mutations, we’ll want to notify users saying: Hey! something went wrong!
RTK query provide hooks to call api and return an error which trigger re-render event, so we can easily integrate our beautiful modal or toast library.
To trigger a notification, we can simply use useEffect to do something when we received any error:
The above example looks good if we have only one component, but what if our applications grows bigger and we don’t want to copy-paste the boilerplate?
From the official document, we can use middleware to trigger our actions whenever we received an error.
However, isn’t it feel like a bit confusing to use a middleware if we don’t want every error to dispatch the same actions? Otherwise we may eventually need to add a huge switch case in the errorMiddleware, and it’s obviously what we want to avoid.
To solve this problem, we can instead create a slice and use addMatcher in extraReducer. @reduxjs/toolkit document have an example showing how to capture a rejected response.
Back to our use case, we want to centralize multiple api error handling, so we can use isAnyOf from @reduxjs/toolkit.
Below is an example of how we can integrate addMatcher with isAnyOf to centralize our api error handling.
- Create a slice and initialize our error state with null.
2. Use a selector to monitor the apiError state and perform your action accordingly:
We can even add more matchers to monitor the loading state or success state. This is how powerful it is!