首页 > 解决方案 > React-query:使用具有不同参数的 useInfiniteQuery 进行新查询

问题描述

我正在设置 useInfiniteQuery 以从 Github Jobs API 获取作业。我还没有使用加载更多按钮设置实际的无限查询,但现在我想了解如何从 useInfiniteQuery 返回的数据中重置信息并使用我目前使用的新参数进行新查询使用 react-hook-forms 设置的状态。

  const [page, setPage] = useState(1);
  const [searchParams, setSearchParams] = useState({
    text: '',
    location: '',
    fullTime: false
  });

  const fetchJobs = async (key, page = 1) => {
    const { text, location, fullTime } = searchParams;
    try {
      const res = await fetch(
        `https://api.allorigins.win/get?url=${encodeURIComponent(
          `https://jobs.github.com/positions.json?description=${text}&page=${page}&location=${location}&full_time=${fullTime}`
        )}`
      );
      const json = await res.json();
      const results = JSON.parse(await json.contents);
      return {
        results,
        nextPage: page + 1
      };
    } catch (error) {
      console.log(error);
    }
  };

  const {status, data, error, isFetching, isFetchingMore, fetchMore, canFetchMore
  } = useInfiniteQuery('jobs', fetchJobs, {
    getFetchMore: (lastGroup, allGroups) => lastGroup.nextPage
  });

  const onSubmit = async data => {
    const { text, location, fullTime } = data;
    setSearchParams({
      text,
      location,
      fullTime
    });
    // Want to make a new query call to fetch new Jobs with different parameters

    // Using refetchOnWindowFocus uses the parameters from the new searchParams state,
    // but using useQueryCache.refetchQueries() here does not, neither does
    // expecting fetchJobs to get the updated state, as fetchJobs seems to always use the
    // initial searchParams state
  };

  return (
    <>
      <Search onSubmit={handleSubmit(onSubmit)} ref={register} />
      {isFetching && <p>Loading...</p>}
      {data && <p>Got data</p>}
    </>
  );

正如所评论的,当我尝试提交表单时,状态会更新,但 fetchJobs 永远不会获得更新的状态。

任何帮助,将不胜感激。

标签: reactjs

解决方案


您需要将任何可能更新的数据作为数组形式的查询参数的一部分作为键传递。或与表单数据的深度相等。

const {status, data, error, isFetching, isFetchingMore, fetchMore, canFetchMore
  } = useInfiniteQuery(['jobs', text, location, fullTime], fetchJobs, {
    getFetchMore: (lastGroup, allGroups) => lastGroup.nextPage
  });

链接以获取更多信息 https://react-query.tanstack.com/guides/query-functions


推荐阅读