我正在研究react-query,但找不到一个特定用例的示例。
演示todo API服务器返回以下JSON for getTodos(ifModifiedSince=1234567)
请求:
如果自指定时间以来未修改待办事项列表:{"status":"not_modified"}
否则:{"status":"ok","todos":[{"userId":1,"id":2,"title":"TodoItem1","completed":false}],"lastModified":"1234589"}
我想到的最接近的:
const { isLoading, isError, data } = useQuery(
[todosQueryKey],
() => {
const lastModified = data?.lastModified || '';
const result = getTodos({
ifModifiedSince: lastModified,
});
return result;
},
{
select: (newData): GetTodosResponse | undefined => {
let resolvedData = newData;
if (newData.status === StatusNotModified) {
//! This actually does not work because getQueryData
//! already returns data from most recent 'not_modified' request.
resolvedData = queryClient.getQueryData([todosQueryKey]) || newData;
}
resolvedData.todos?.sort((a: TodoItem, b: TodoItem) => b.id - a.id);
return resolvedData;
},
refetchInterval: 5000,
staleTime: Infinity,
keepPreviousData: true,
}
);
使用React查询完成上述任务的正确方法是什么?
1条答案
按热度按时间aiazj4mn1#
我目前的解决方案是像往常一样使用
useQuery()
,但修改getTodos()
函数,使其接收缓存数据作为可选的第二个参数,并在status==='not_modified'
: