RTK Query not passing headers

I have an RTK Query api like below

export const wireguardApi = createApi({
    reducerPath: 'wireguardApi',
    baseQuery: fetchBaseQuery({
        baseUrl: '/api/',
        prepareHeaders: (headers, { getState }) => {
            const token = (getState()).auth.access?.token;
            if (token)
                headers.set('authorization', `Bearer ${token}`);
            return headers;
        },
    }),
    endpoints: (builder) => ({
        getAllServers: builder.query({
            query: () => `wg/servers/`,
        }),
        obtainRefreshToken: builder.mutation({
            query: (formData) => ({
                url: `auth/token/obtain/`,
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: formData,
            }),
        }),
    }),
});

And call it on my page using

const { data: servers, error, isLoading, refetch, isFetching } = useGetAllServersQuery();

Yet, when the page loads, executing the query, it doesn't pass the authorization header. Why?

1 answer

  • answered 2022-04-05 04:50 ishantiwari

    I also faced the same issue

    The problem is that access token is unavailable when the query starts Make sure that adding the token executes before making queries. (You can check the sequence in Redux DevTools)

    ScreenShot of ReduxDevTools

    Here addFromLocalStorage executes before starting the query

    Earlier I was using react useEffect to dispatch the action. Then the query started before adding the token

    What then I did was

    store.dispatch(addFromLocalStorage())
    

    in main.js or index.js where you've rendered your App.

    This makes sure that access token is added before executing any query in your React App.

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum