reactjs - 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 永远不会获得更新的状态。
任何帮助,将不胜感激。
解决方案
您需要将任何可能更新的数据作为数组形式的查询参数的一部分作为键传递。或与表单数据的深度相等。
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
推荐阅读
- c++ - 模板别名 - 问题(C++ 之旅)
- django - 如何从 ManyToMany 字段 Django 中获取所有属性数据?
- flutter - Dart 基础:访问类参数
- javascript - 如何从 dict 数组中提取一些数据以放入数组中?
- python - pandas.DataFrame 使用 numpy.select() 和 .shift() 引用前一行的值
- javascript - list.js 中的多个过滤器?
- python - Google Colab 和 IBM Watson Studio 中的代码相同但结果不同
- node.js - 续集“反向”hasOne?
- c# - +intCounter 在 Visual Studio 中生成错误 CS0201
- mysql - 使参与日期范围的小时数总和