TanStackT
TanStack2y ago
7 replies
slow-yellow

optimistic update not updating dom

Im trying to optimistically update an item in an array but it doesnt trigger an update in the dom.

My response of the query is something like
const data = {
  data: [{ id: '1', name: 'test' }],
  meta: { pages: 1, ... } 
}


and is fetched via the api, lets simply for now
const query = useQuery({
  queryKey: ['users'],
  queryFn: () => return data
})


now i have an update function where i want to update that user optimistically
const toggleMutation = useMutation({
  mutationFn: (uuid: string) => ...updateUser
  onMutate: async (uuid) => {
    const previousUsers = queryClient.getQueryData(['users'])

    if (previousUsers) {
      for (const user of previousUsers.data) {
        if (user.uuid === uuid) {
          user.name = 'test1'
        }
      }
      queryClient.setQueryData(['users'], previousUsers)
    }

    // Return a context with the previous and new user
    return { previousUser, previousUsers, queryKey }
  }
})


Doing this will update the data that i see in the devtools, but wont trigger an update in the dom,
Updating a value in the root object will trigger an update
  queryClient.setQueryData(['users'], { data: [], ...previousData })

for example works
Was this page helpful?