Home > front end >  React Hooks must be called in a React function component when using React RTK query createApi
React Hooks must be called in a React function component when using React RTK query createApi

Time:02-27

I'm creating 2 endponits using React RTK query

export const countryApi = createApi({
    reducerPath: "countryApi",
    baseQuery: fetchBaseQuery({ baseUrl: "https://restcountries.com/v3.1/" }),
    endpoints: (builder) => ({
    getCountries: builder.query({
    query: () => `all/`
    }),
   getCountryByName: builder.query({
    query: (name) => `name/${name}`
    })
  })
});

Then i need to show results with condition, if the state of search input change i call the second endponit otherwise i use the 1st enpoint to show all the list of countries

// country search state
const [search, setSearch] = useState("");
let countryData;
countryData =
  search === ""
    ? useGetCountriesQuery().data
    : useGetCountryByNameQuery(search,{skip: search ===""}).data;

But i got an error enter image description here

CodePudding user response:

You cannot call hooks conditionally, that is against the rules of hooks.

hooks must be called every time, in the same order, when a render functions runs. By having that ternary, this is not guaranteed to happen:

countryData =
  search === ""
    ? useGetCountriesQuery().data
    : useGetCountryByNameQuery(search,{skip: search ===""}).data;

You might call useGetCountriesQuery in one render cycle, and useGetCountryByNameQuery in another.

One way to solve this would be to call both hooks unconditionally, but skip them vice-versa. Or, combine the two queries into one hook if possible:

const countries = useGetCountriesQuery({ skip: search !== '' })
const countriesByName = useGetCountryByNameQuery(search,{skip: search ===""})

const countryData = search === "" ? countries.data : countriesByName.data
  • Related