New to Typescript, I thought this would have been a common problem, couldn’t really find anything helpful
Here’s my API slice
import { createApi, fetchBaseQuery } from "@reduxjs/toolkit/query/react";
export const apiSlice = createApi({
reducerPath: "apiSlice",
prepareHeaders: (headers) => {
headers.set("Content-Type", "application/json");
headers.set("Access-Control-Allow-Origin", "*");
return headers;
},
baseQuery: fetchBaseQuery({
baseUrl: "https://api.npoint.io",
}),
endpoints: (builder) => ({
getWines: builder.query({
query: () => `/0d9ec2e70191f0835e9a`,
}),
}),
});
export const { useGetDataQuery } = apiSlice;
PrepareHeaders Error
Object literal may only specify known properties, and ‘prepareHeaders’ does not exist in type ‘CreateApiOptions<BaseQueryFn<string | FetchArgs, unknown, FetchBaseQueryError, {}, FetchBaseQueryMeta>, { getWines: QueryDefinition<any, BaseQueryFn<…>, never, any, “apiSlice”>; }, “apiSlice”, never>’.ts(2353)
UserGetDataQuery Error
Property ‘useDataQuery’ does not exist on type ‘Api<BaseQueryFn<string | FetchArgs, unknown, FetchBaseQueryError, {}, FetchBaseQueryMeta>, EndpointDefinitions, “apiSlice”, never, unique symbol | unique symbol>’.ts(2339)
prepareHeader
is part of the fetchBaseQuery
function API, not createApi
. Move the prepareHeaders
property into fetchBaseQuery
.
Example:
import { createApi, fetchBaseQuery } from "@reduxjs/toolkit/query/react";
export const apiSlice = createApi({
reducerPath: "apiSlice",
baseQuery: fetchBaseQuery({
baseUrl: "https://api.npoint.io",
prepareHeaders: (headers) => {
headers.set("Content-Type", "application/json");
headers.set("Access-Control-Allow-Origin", "*");
return headers;
},
}),
endpoints: (builder) => ({
getWines: builder.query<ReturnValueTypeHere, void>({
query: () => `/0d9ec2e70191f0835e9a`,
}),
}),
});
There isn’t any getData
endpoint declared so there will not be any useGetDataQuery
hook generated. Given the code above only useGetWines-X
hooks will be generated, e.g. useGetWinesQuery
.
export const { useGetWinesQuery } = apiSlice;