【问题标题】:How to set lastPage.nextCursor in useInfiniteQuery hook of react Query如何在 react Query 的 useInfiniteQuery 钩子中设置 lastPage.nextCursor
【发布时间】:2022-10-15 15:57:13
【问题描述】:

我的无限查询钩子看起来像这样

const {
    data,
    error,
    isSuccess,
    hasNextPage,
    fetchNextPage,
    isFetchingNextPage
  }=useInfiniteQuery(
    'test',
    ({ pageParam = 1 }) => fetchData(pageParam, 14),
    {
      getNextPageParam: (lastPage: any, allPages: any) => {
        console.log('endCursor', lastPage.nextCursor);
        if (hasNextPage) {
          console.log('Returning from keep fetching', lastPage.nextCursor);
          return lastPage.nextCursor;
        }
        return undefined;
      }
    }
  );

我的 fetch 函数看起来像这样

const fetchData = async (page = 1, pageSize: any, variables?: string) => {
    console.log('Inside fetch data for new schema');
    const res = await graphQLClient.request(
      QUERY,
      variables,
      requestHeaders
    );
    console.log('res', res);
    return {
      pages: res.getCustomerLibrary.books.edges,
      hasNextPage: res.data.books.pageInfo.hasNextPage,
      lastPage: { nextCursor: res.data.books.pageInfo.endCursor },
      nextPage: res.data
    };
  };

数据正常,但我的问题是如何更新 lastPage.nextCursor 以便我可以在 useInfiniteQuery 挂钩中使用它。

现在它对所有页面都未定义。

另外,我是不是做错了什么,因为数据没有正确返回,无论我从 fetchData 函数返回什么,一切都在数据的 pages 变量中,我想要的是:

  • 从 fetch 函数返回的 pages 变量应该转到 pages
  • 从 fetch 函数返回的hasNextPage 应该填充infiniteQuery 的hasNextPage 挂钩
  • lastPage.nextCursor 应该填充到 pageParam 中,以便我可以使用它来获取下一页

【问题讨论】:

    标签: reactjs react-query


    【解决方案1】:

    您不能在queryFn 中使用hasNextPage,因为它是从useInfiniteQuery 返回的结果。 hasNextPage 派生自您从 getNextPageParam 返回的内容,因此这将是循环的。

    你的fetchData 函数返回一个nextCursor,那么为什么不检查一下呢?如果是undefined,则没有下一页,所以返回undefined,否则返回nextCursor

    另请注意,您进入的lastPage getNextPageParam 正是您的 queryFn 返回的类型。如果您不使用any 覆盖类型,您会看到。因此,对于您的结果结构,代码需要是:

    getNextPageParam: (lastPage) => {
      if (lastPage.hasNextPage) {
        return lastPage.lastPage.nextCursor;
      }
      return undefined;
    }
    

    lastPage 看起来很奇怪,但这就是你的 queryFn 返回的内容。当然你可以改变它,扁平化结构然后适应getNextPageParam

    【讨论】:

      猜你喜欢
      • 2022-11-09
      • 2020-05-23
      • 2021-05-29
      • 2021-09-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-08
      • 2021-01-12
      相关资源
      最近更新 更多