2021-07-30

Redux-Toolkit query interceptor

I'm trying to build an interceptor for cases when the access token becomes invalid with RTK Query. I've built it by an example in the docs, so that is looks as follows:

const baseQuery = fetchBaseQuery({
    baseUrl: BASE_URL,
    prepareHeaders: (headers, { getState }) => {
        const {
            auth: {
                user: { accessToken },
            },
        } = getState() as RootState;
        if (accessToken) {
            headers.set('authorization', `Bearer ${accessToken}`);
        }
        return headers;
    },
});

const baseQueryWithReauth: BaseQueryFn<string | FetchArgs, unknown, FetchBaseQueryError> = async (
    args,
    api,
    extraOptions
) => {
    let result = await baseQuery(args, api, extraOptions);

    if (result.error && result.error.status === 401) {
        const refreshResult = await baseQuery('token/refresh/', api, extraOptions);

        if (refreshResult.data) {
            api.dispatch(tokenUpdated({ accessToken: refreshResult.data as string }));

            // retry the initial query
            result = await baseQuery(args, api, extraOptions);
        } else {
            api.dispatch(logout());
        }
    }
    return result;
};

export const baseApi = createApi({
    reducerPath: 'baseApi',
    baseQuery: baseQueryWithReauth,
    endpoints: () => ({}),
});

The problem is that the token/refresh/ expects a POST request with a refresh token its body and I can't figure out how to rebuilt this line const refreshResult = await baseQuery('token/refresh/', api, extraOptions); for it to accept parameters and make POST request.



from Recent Questions - Stack Overflow https://ift.tt/3BX2Lte
https://ift.tt/eA8V8J

No comments:

Post a Comment