Mahmonir Bakhtiyari
Mahmonir Bakhtiyari

Reputation: 605

RTK type Error when using injectedEndpoints with openApi

I define config file for openApi to create automatically endpoints with types:

const config: ConfigFile = {
  schemaFile: 'https://example.com/static/docs/swagger.json',
  apiFile: './api/index.ts',
  apiImport: 'api',
  outputFile: './api/sampleApi.ts',
  exportName: 'sampleApi',
  hooks: true,
}; 
export default config;

I used:

"@rtk-query/codegen-openapi": "^1.0.0-alpha.1"
"@reduxjs/toolkit": "^1.7.2",

Then I define an index.tsx that has

export const api = createApi({
  baseQuery: axiosBaseQuery({ baseUrl: '' }),
  endpoints: () => ({}),
});

and so I generate successfully my sampleApi.tsx file with all of endpoints and types. like here:

const injectedRtkApi = api.injectEndpoints({
  endpoints: (build) => ({
    postUsersCollections: build.mutation<
      PostUsersCollectionsApiResponse,
      PostUsersCollectionsApiArg
    >({
      query: (queryArg) => ({
        url: `/users/collections`,
        method: 'POST',
        body: queryArg.postCollectionBody,
      }),
    }),
    getUsersCollections: build.query<
      GetUsersCollectionsApiResponse,
      GetUsersCollectionsApiArg
    >({
      query: (queryArg) => ({
        url: `/users/collections`,
        params: { name: queryArg.name },
      }),
    }),
    overrideExisting: false,
  });
});
export const {
  usePostUsersCollectionsMutation,
  useGetUsersCollectionsQuery
} = injectedRtkApi;
  1. When in a component I use hook function useGetUsersCollectionsQuery as below I got an error that TypeError: Cannot read properties of undefined (reading 'subscriptions'). There is no lint typescript error related to typescript in my project.

    const { data: collectionData = [] } = useGetUsersCollectionsQuery({});
    

    It's interesting that this hook is called and I see API call in network tab but immediately I got this error. If I remove this line, the error disappears.

  2. And also for mutation hook I send data within it but I got 400 error, as below:

    const [postCollection, { data: newCollect }] =
        usePostUsersCollectionsMutation();
        ...
    const handleCreateItem = async () => {
      const response: any = await postCollection({
        postCollectionBody: { name: 'sample' },
      });
    }
    

Upvotes: 2

Views: 1614

Answers (1)

Mahmonir Bakhtiyari
Mahmonir Bakhtiyari

Reputation: 605

Finally I resolved it!
I should define reducerPath as this:

export const api = createApi({ 
  reducerPath: 'api', // <=== add this and define `api` in reducers
  baseQuery: axiosBaseQuery({ baseUrl: '' }),
  endpoints: () => ({}),
});

Upvotes: 3

Related Questions