rtk-incubator / rtk-query

Data fetching and caching addon for Redux Toolkit
https://redux-toolkit.js.org/rtk-query/overview
MIT License
626 stars 31 forks source link

Http response codes in rejected actions #233

Closed simonauner closed 3 years ago

simonauner commented 3 years ago

Hi!

I guess this is a feature request or a question, perhaps it's already possible and I'm just not finding the correct documentation.

I'd like to implement a global middleware for handling 401s from the server and dispatching a logout action.

Looking at the macro level error handling example I would like to do something like this:

import { loggedOut } from './userActions';

const UnauthorizedMiddleware = (store) => (next) => (action) => {
    if (isRejected(action) && action.error.status === 401) {
          store.dispatch(loggedOut());
    }

    // continue processing this action
    return next(action);
};

I would like to know the Http response code in this context so that I can handle specific error codes globally in the application. Is it possible to provide this?

phryneas commented 3 years ago

Try isRejectedWithValue instead of isRejected and looking at action.payload.status

simonauner commented 3 years ago

Ah, yes, there it was. I stared at that action object for minutes without thinking about looking at payload :(

isRejectedWithValue didn't seem to work (perhaps because my server sends 401 without body?), but isRejected and action.payload.status works! Thanks!

phryneas commented 3 years ago

if isRejectedWithValue does not work, that would be a bug in Redux-Toolkit, since payload will be undefined unless this is a "known error" handled with rejectWithValue.

Can you share one of those actions (full action body) that work with isRejected, but not with isRejectedWithValue please?

simonauner commented 3 years ago

You're correct, it works with isRejectedWithValue as well... I've must have been debugging the wrong action :thinking:

phryneas commented 3 years ago

Okay, good you solved it :+1: I'm gonna close this now. If you have any more usage questions, come over to #redux on Reactiflux :smiley: