更新配置文件运行良好,但乐观更新不能正常工作。发生的错误“旧不可迭代”。怎么解决这个问题?
export const useUpdateProfile = () => {
const queryClient = useQueryClient();
return useMutation(updateProfile, {
onMutate: async (newProfile) => {
// Cancel any outgoing refetches (so they don't overwrite our optimistic update)
await queryClient.cancelQueries("user-profile");
// Snapshot the previous value
const previousProfile = queryClient.getQueryData("user-profile");
// Optimistically update to the new value
queryClient.setQueryData(["user-profile"], (old) => [...old, newProfile]);
// Return a context object with the snapshotted value
return { previousTodos };
},
// If the mutation fails, use the context returned from onMutate to roll back
onError: (err, newTodo, context) => {
queryClient.setQueryData("user-profile", context.previousProfile);
},
// Always refetch after error or success:
onSettled: () => {
queryClient.invalidateQueries("user-profile");
},
});
};发布于 2022-07-27 16:44:09
似乎获取user-profile会给您返回undefined,可能是因为它不存在吗?在传播之前,一定要检查undefined:
// Optimistically update to the new value
queryClient.setQueryData(["user-profile"], (old) => old ? [...old, newProfile] : []);如果您已经升级到v4 (@tan堆栈/ the query),还可以从更新程序返回未定义的内容以退出更新:
queryClient.setQueryData(["user-profile"], (old) => old ? [...old, newProfile] : undefined);https://stackoverflow.com/questions/73116110
复制相似问题