Search code examples
reactjsreact-reduxredux-toolkitrtk-query

error with getting the state in RTK query


I want to access the token which is located in a store and put it in header so to use future queries, but there is error with getState(). here is code->

import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'

export const baseApi = createApi({
    reducerPath: "baseApi",
    tagTypes: ["Todos"],
    baseQuery: fetchBaseQuery({
        baseUrl: 'http://localhost:3000/',
        prepareHeaders: (headers, { getState }) => {
            const token = getState().auth.accessToken;
            if (token) {
                headers.set('Authorization', `Bearer ${token}`)
            }
            return headers;
        },
    }),
    endpoints: () => ({
        
    }),
    [error](https://i.sstatic.net/nMjl3.png)
});

the Vscode show (parameter) getState: () => unknown Object is of type 'unknown'


Solution

  • Based on the documentation here

    https://redux-toolkit.js.org/rtk-query/api/fetchBaseQuery#setting-default-headers-on-requests

    try to cast the getstate() call with your state type.

    const token = (getState() as RootState).auth.token