TanStackT
TanStack6h ago
13 replies
urgent-maroon

Polling & optimistic updates

I wonder if there is a best practice when combining polling & optimistic updates. Below an example I found in the react-query course (ui.dev):

function useToggleTodo(id, sort) {
  const queryClient = useQueryClient()

  return useMutation({
    mutationFn: () => toggleTodo(id),
    onMutate: async () => {
      await queryClient.cancelQueries({
        queryKey: ['todos', 'list', { sort }]
      })

      const snapshot = queryClient.getQueryData(
        ['todos', 'list', { sort }]
      )

      queryClient.setQueryData(
        ['todos', 'list', { sort }],
        (previousTodos) => previousTodos?.map((todo) =>
          todo.id === id ? { ...todo, done: !todo.done } : todo
        )
      )

      return () => {
        queryClient.setQueryData(
          ['todos', 'list', { sort }],
          snapshot
        )
      }
    },
    onError: (error, variables, rollback) => {
      rollback?.()
    }
  })
}

function useTodos(sort) {
  const queryClient = useQueryClient()

  return useQuery({
    queryKey: ['todos', 'list', { sort }],
    queryFn: () => fetchTodos(sort),
  })
}


What happens if a
refetchInterval
of 5 seconds is added to the
useQuery
of useTodos and that interval is triggered:

1) Just before useToggleTodo is triggered, will
cancelQueries
also work here?
2) Just after
cancelQueries
from useToggleTodo ran, will the polled useTodos data overwrite the optimistic update?
3) ...?

I just wonder if there is a some pattern when dealing with this scenario.
Was this page helpful?