javascript 使用React Spring动画进行React查询乐观更新

cygmwpex  于 2023-01-01  发布在  Java
关注(0)|答案(1)|浏览(110)
    • bounty将在6天后过期**。回答此问题可获得+50的声望奖励。kabukiman正在寻找规范答案

我正在使用react查询变异来创建一个对象并乐观地更新UI

const queryClient = useQueryClient()

useMutation({
    mutationFn: updateTodo,
    onMutate: async newTodo => {
        await queryClient.cancelQueries({ queryKey: ['todos'] })
        const previousTodos = queryClient.getQueryData(['todos'])

        // Optimistically update to the new value
        queryClient.setQueryData(['todos'], old => [...old, newTodo])

        return { previousTodos }
    },
    onError: (err, newTodo, context) => {
        queryClient.setQueryData(['todos'], context.previousTodos)
    },
    onSettled: () => {
        queryClient.invalidateQueries({ queryKey: ['todos'] })
    },
})

新的内存中的待办事项有一些随机的ID和显示在用户界面与ReactSpring动画。然后我从服务器得到响应与成功确认和真正的待办事项ID。我的应用程序更换和重新动画用户界面元素,这是问题。乐观更新是必须具备的功能,但我不知道如何停止这种行为。需要帮助

fnvucqvd

fnvucqvd1#

可以使用“onSuccess”回调函数更新查询数据。

const queryClient = useQueryClient()
useMutation({
 mutationFn: updateTodo,
 onMutate: async newTodo => {
    await queryClient.cancelQueries({ queryKey: ['todos'] })
    const previousTodos = queryClient.getQueryData(['todos'])

    // Optimistically update to the new value
    queryClient.setQueryData(['todos'], old => [...old, newTodo])

    return { previousTodos }
},
onError: (err, newTodo, context) => {
    queryClient.setQueryData(['todos'], context.previousTodos)
},
onSuccess: (data, newTodo) => {
    // Update the query data with the real todo item ID from the server response
    queryClient.setQueryData(['todos'], old => old.map(todo => todo.id === newTodo.id ? data.todo : todo))
},
onSettled: () => {
    queryClient.invalidateQueries({ queryKey: ['todos'] })
},})

相关问题