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

Comments

Popular posts from this blog

Today Walkin 14th-Sept

Spring Elasticsearch Operations

Hibernate Search - Elasticsearch with JSON manipulation