How to resubmit the request after refreshing the token?

399 views Asked by At

The situation: I send a request to receive some data and receive a response that the token has expired. Next, I have to update the token and resend the request that I sent at the beginning. How to do it using redux-toolkit and middleware?

Middleware for catching errors:

import { doRefreshToken } from "../reducers/user";

const TOKEN_EXPIRED_ERROR = "tokenExpiredException";

const tokenMiddleware = (api) => (next) => (action) => {
    const result = next(action);

    if (action.type === TOKEN_EXPIRED_ERROR) {
        const refreshToken = localStorage.getItem("refreshToken");
        api.dispatch(doRefreshToken({ refreshToken })).then(() => {
            // dispatch new action
        });
    }

    return result;
};

export default tokenMiddleware;

The request to send after refreshing the token:

const getSmth = createAsyncThunk("user/getSmth ", async (_, { rejectWithValue }) => {
    try {
        const response = await api.get("/smth");
        return response;
    } catch (error) {
        return rejectWithValue(error.response);
    }
});

Important: to be able to send not only a getSmth request, but also any other one, and you also need to do this in the middleware

1

There are 1 answers

0
LutherW On

You can give the dispatch like argument on your calling middleware and dispatch an new action directly inside :

origin call :

dispatch(tokenMiddleware(dispatch, ...otherArgument...))

in middleware :

.then(() => dispatch(getSmth())