Home > Back-end >  redux-toolkit prepareHeaders is not a function
redux-toolkit prepareHeaders is not a function

Time:10-05

I have issues when I use this query, it says that prepareHeaders is not a function but I added it as an object as you can see in my code below:

const access_token = localStorage.getItem('rs_access_token');
// Define a service using a base URL and expected endpoints
export const lfApi = createApi({
    reducerPath: 'lfApi',
    baseQuery: fetchBaseQuery({
        baseUrl: 'http://homestead.test/api/v1',
        prepareHeaders: {
            'Authorization': `Bearer ${access_token}`,
            'Content-Type': 'application/json',
            'Accept': 'application/json',
        },
    }),
    endpoints: (builder) => ({
        getUser: builder.query({
            query: (params) => `user`,
        }),
        getAgent: builder.query({
            query: (params) => `myagents/agents/${params}`,
        }),
    }),
});

// Export hooks for usage in functional components, which are
// auto-generated based on the defined endpoints
export const { useGetUserQuery } = lfApi;
export const { useGetAgentQuery } = lfApi;

enter image description here

CodePudding user response:

It's because the prepareHeaders property - as the error message says - accepts a function, not an object. You can see from the example here.

const baseQuery = fetchBaseQuery({
  baseUrl: '/',
  prepareHeaders: (headers, { getState }) => {
    headers.set('Authorization', `Bearer ${access_token}`);
    headers.set('Content-Type', 'application/json');
    headers.set('Accept', 'application/json');

    return headers
  },
})
  • Related