I'm using RTK (Redux Toolkit) and RTK Query to manage my store and API requests.
To catch errors globally, I followed this example. That works fine, but now I'd like to log out the user when a request was rejected because of a 401 - Unauthorized-error.
const rtkQueryErrorLogger = api => next => action => {
if (isRejectedWithValue(action)) {
if (action.payload.status === 401) {
// Reset the store (not working)
const dispatch = useDispatch();
const dipatch(logout());
// Forward to login-screen (not working)
const navigation = useNavigation();
navigation.push('Login');
}
}
return next(action);
};
Any idea? Thanks in advance!
A Redux middleware always gets a "mini-store API" object as the argument to the outermost function, which contains {dispatch, getState}:
https://redux.js.org/tutorials/fundamentals/part-4-store#writing-custom-middleware
In this case, it's the variable named api in your example.
You can access dispatch from that object and dispatch an action at any time inside your middleware. Just delete the const dispatch = useDispatch line, and either change the next line to api.dispatch() or destructure dispatch from the api object in the declaration.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With