1

I have a hook that pulls some data and does some other stuff:

const search = useSearcher(...);

Hook itself sends API requests and updates its search state as necessary - clears search state if search query is empty string, cancels requests, sets search results if request was successful, sets loading state, state of when search is successful but there were no matching results, and so on. Basically, in const search there will be complete state of search:

{
searchResults, //T[]
isLoading, //boolean
isNoMatchingResult, //boolean
searchInputValue, //string
resetSearchResults,// ()=>void
...
}

I want to use it to pull data for useInfiniteQuery like this:

const { status, data, error, isFetching, isFetchingNextPage, fetchNextPage, hasNextPage } =
    useInfiniteQuery('projects', (ctx) => useSearcher(ctx.pageParam), {
      getNextPageParam: (_lastGroup, groups) => groups.length,
    });

I get the following error:

React Hook "useSearcher" cannot be called inside a callback. React Hooks must be called in a React function component or a custom React Hook function

I understand that hooks can't be called from callbacks, only from components directly, but how do I solve this problem? Are there any options other than extracting data requesting code from useSearcher hook into separate method?

user2363676
  • 331
  • 2
  • 10
  • What does `useSearcher` do? You may need to extract the code from it like you said, or maybe you just need to return something from it instead, but we'll need to see how it's implemented to make a recommendation. – Nicholas Tower Sep 01 '23 at 18:32
  • @NicholasTower updated question – user2363676 Sep 01 '23 at 18:45

0 Answers0