javascriptreactjsaxiosreact-query

How to pass more parameters in useInfiniteQuery?


I am using React query useInfiniteQuery to get more data

const { data, isLoading, fetchNextPage, hasNextPage, error, isFetching } =
useInfiniteQuery("listofSessions", listofSessions, {
  getNextPageParam: (lastPage, pages) => {
    if (lastPage.length < 10) return undefined;
    return pages.length + 1;
  },
});

API requests:

const listofSessions = async ({ groupId, pageParam = 1 }) =>
  await axios
    .get(`${apiURL}/groups/allsessions`, {
      params: {
        groupId: 63,
        page: pageParam,
      },
    })
    .then((res) => {
      return res.data.data;
    });

I want to pass groupId to listofSessions API function like that:

const { data, isLoading, fetchNextPage, hasNextPage, error, isFetching } =
    useInfiniteQuery("listofSessions", listofSessions({groupId}), ....

But I get an error

Missing queryFn

How can I solve this problem of passing multiple parameter values in useInfiniteQuery?


Solution

  • Pass a new function, instead of calling it.

      const listofSessions = async ({ groupId, pageParam = 1 }) =>
          await axios
            .get(`${apiURL}/groups/allsessions`, {
              params: {
                groupId: 63,
                page: pageParam,
              },
            })
            .then((res) => {
              return res.data.data;
            });
    
        // pass a new function
        const { data, isLoading, fetchNextPage, hasNextPage, error, isFetching } =
        useInfiniteQuery(
       ["listofSessions", groupId, moreSearchParams], 
       ({ pageParam = 1 }) => listofSessions({ groupId, pageParam}), 
       {
          getNextPageParam: (lastPage, pages) => {
            if (lastPage.length < 10) return undefined;
            return pages.length + 1;
       },
        });
    

    Edit: Please include dependencies in the query key InfiniteQuery(["listofSessions", groupId, moreSearchParams], so that the cache is valid for the search parameters. Thanks @TkDodo for pointing it out and improving the answer

    If it is possible to refer to groupId inside listofSessions that would be a simpler solution.