Search code examples
typescriptreact-nativereact-hooksredux-toolkitrtk-query

RTK Query createApi() endpoints not showing up as hooks in Typescript


Trying a simple base query with RTK Query and after defining my api with createApi(), Typescript is giving me error when I try to destructure the api to get my hooks.

I then copied pasted the pokemon example code from the docs and even with that, it's saying the hook doesn't exist.

Clearly I'm missing something.

Here's the code, pulled right from the docs but with a string return type:

export const pokemonApi = createApi({
    reducerPath: 'pokemonApi',
    baseQuery: fetchBaseQuery({ baseUrl: 'https://pokeapi.co/api/v2/' }),
    endpoints: (builder) => ({
      getPokemonByName: builder.query<string, string>({
        query: (name) => `pokemon/${name}`,
      }),
    }),
})
  
export const { useGetPokemonByNameQuery } = pokemonApi;

That useGetPokemonByNameQuery is what shows the error:

Property 'useGetPokemonByNameQuery' does not exist on type 'Api<BaseQueryFn<string | FetchArgs, unknown, FetchBaseQueryError, {}, FetchBaseQueryMeta>, { getPokemonByName: QueryDefinition<...>; }, "pokemonApi", never, unique symbol>'.

What am I doing wrong?


Solution

  • @reduxjs/toolkit: 1.9.5

    From the /rtk-query/api/created-api/overview#react-hooks doc:

    The core RTK Query createApi method is UI-agnostic, in the same way that the Redux core library and Redux Toolkit are UI-agnostic. They are all plain JS logic that can be used anywhere.

    However, RTK Query also provides the ability to auto-generate React hooks for each of your endpoints. Since this specifically depends on React itself, RTK Query provides an alternate entry point that exposes a customized version of createApi that includes that functionality

    If you have used the React-specific version of createApi, the generated Api slice structure will also contain a set of React hooks.

    The same hooks are also added to the Api object itself, and given auto-generated names based on the endpoint name and query/mutation type.

    Make sure the createApi function import from the below path:

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

    NOT:

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

    The full example can be found here