react-hooksredux-toolkit

Redux RTK not auto-generating react hooks


Could not find any info on this that explains why its not generating and how to force it to re-generate these hooks.

First I thought I had to run the app to get it to work so did yarn start.

I ended up manually adding them at the bottom export where it should auto-generate according to the documentation. I following this comment here.

Hooks are automatically generated based on the name of the endpoint in the service definition. An endpoint field with getPost: builder.query() will generate a hook named useGetPostQuery.

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

// Define a service using a base URL and expected endpoints
export const pokemonApi = createApi({
  reducerPath: 'pokemonApi',
  baseQuery: fetchBaseQuery({ baseUrl: 'https://pokeapi.co/api/v2/' }),
  endpoints: (builder) => ({
    getPokemonByName: builder.query<Pokemon, string>({
      query: (name) => `pokemon/${name}`,
    }),
    getMyNewCustomEndpoint: builder.query<Pokemon, string>({
      query: (name) => `pokemon/${name}`,
    }),
  }),
})
// Export hooks for usage in functional components, which are
// auto-generated based on the defined endpoints
export const { useGetPokemonByNameQuery, useGetMyNewCustomEndpoint } = pokemonApi

notice the useGetMyNewCustomEndpoint which I added myself.

Then when I import I see:

import { useGetMyNewCustomEndpoint } from './services/pokemon'

and when I hover over it in my IDE I do see the properties I can use. Tried this with mutations too. Seems to work (confused from all this magic~)

Anyways, the question is still on the title of this post, how do you get the auto-generating to work. Probably missing something simple.


Solution

  • You misread that.

    It is automatically generating the hook pokemonApi.useGetPokemonByNameQuery. You define an endpoint and then that property exists on pokemonApi. That's all.

    You will have to export that by hand - there is no magic in place to change your files.