Saturday 31 December 2022

React Query optimistic update with React Spring animation

I'm using react query mutation to create an object and update UI optimistically

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'] })
    },
})

New in-memory todo item have some random ID and displayed in UI with React Spring animation. Then i get response from server with success confirmation and real todo item ID. My application replaces and reanimates UI element and this is the problem. Optimistic update is must-have feature, but i don't know how to stop this behaviour. Need help



from React Query optimistic update with React Spring animation

No comments:

Post a Comment