我真的不知道怎么问清楚,但我会先粘贴我的代码,然后在下面问。
function useToDos() {
const queryCache = useQueryCache();
const fetchTodos = useQuery(
'fetchTodos',
() => client.get(paths.todos).then(({ data }: any) => data),
{ enabled: false }
);
const createTodo = async ({ name ) =>
await client.post(paths.todos, { name }).then(({ data }) => data);
return {
fetchTodos,
createTodo: useMutation(createTodo, {
onMutate: newItem => {
queryCache.cancelQueries('fetchTodos');
const previousTodos = queryCache.getQueryData('fetchTodos');
queryCache.setQueryData('fetchTodos', old => [
...old,
newItem,
]);
return () => queryCache.setQueryData('fetchTodos', previousTodos);
},
}),
};
}
如您所见,我正在尝试创建自己的自定义钩子(Hook)来包装 react 查询功能。因此,我需要将我的 fetchTodos
查询设置为禁用,这样它就不会立即运行。但是,这会破坏所有后台数据获取吗?
具体来说,当我运行 createTodo
并且 onMutate
方法触发时,我希望在后台更新 fetchTodos
查询,这样我在前端的待办事项列表已更新,无需再次发出请求。但似乎查询最初设置为禁用,后台更新没有生效。
因为我不认为将 react-query hooks 包装到自定义 hooks 库中是一个非常好的主意,我可能会对相同的设置有更多问题,但现在,我将从这里开始。谢谢。 😊
最佳答案
突变不会自动触发重新获取。使用 react-query 实现此目的的方法是通过 queryCache.invalidateQueries在突变后使缓存无效。来自文档:
The invalidateQueries method can be used to invalidate and refetch single or multiple queries in the cache based on their query keys or any other functionally accessible property/state of the query. By default, all matching queries are immediately marked as stale and active queries are refetched in the background.
因此您可以配置 useMutation
以在突变稳定时使查询无效。示例:
function useToDos() {
const queryCache = useQueryCache();
const fetchTodos = useQuery(
'fetchTodos',
() => client.get(paths.todos).then(({ data }: any) => data),
{ enabled: false }
);
const createTodo = async ({ name ) =>
await client.post(paths.todos, { name }).then(({ data }) => data);
return {
fetchTodos,
createTodo: useMutation(createTodo, {
onMutate: newItem => {
queryCache.cancelQueries('fetchTodos');
const previousTodos = queryCache.getQueryData('fetchTodos');
queryCache.setQueryData('fetchTodos', old => [
...old,
newItem,
]);
return () => queryCache.setQueryData('fetchTodos', previousTodos);
},
onSettled: () => {
cache.invalidateQueries('fetchTodos');
}
}),
};
}
关于reactjs - React-Query 和查询失效问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63968683/