Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React & RTK: How to dispatch from a middleware?

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!

like image 726
Mr. B. Avatar asked Jul 24 '26 02:07

Mr. B.


1 Answers

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.

like image 196
markerikson Avatar answered Jul 26 '26 19:07

markerikson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!