Tara
Tara

Reputation: 311

React Query queryClient.setQueryData isn't updating the cached data

I have a custom hook that looks something like this:

import { useQuery, useQueryClient } from 'react-query'
import { get } from '@/util/api' // Custom API utility
import produce from 'immer' // Using immer for deep object mutation

export function useData() {
  const queryClient = useQueryClient()
  const { data, isSuccess } = useQuery(
    'myData', () => get('data')
  )

  function addData(moreData) {
    const updatedData = produce(data.results, (draft) => {
      draft.push(moreData)
    })
    setData(updatedData)
  }

  function setData(newData) {
    queryClient.setQueryData('myData', newData)
  }

 return {
    data: data && data.results,
    setData,
    addData,
 }

}

My data in data.results is an array of objects. When I call addData it creates a copy of my current data, mutates it, then calls setData where queryClient.setQueryData is called with a new array of objects passed in as my second argument. But my cached data either doesn't update or becomes undefined in the component hooked up to the useData() hook. Does anyone know what I'm doing wrong?

Upvotes: 1

Views: 5180

Answers (1)

TkDodo
TkDodo

Reputation: 29056

code looks good from react-query perspective, but I'm not sure if that's how immer works. I think with your code, you will get back the same data instance with just a new data.results object on it. I would do:

const updatedData = produce(data, (draft) => {
  draft.results.push(moreData)
})

Upvotes: 1

Related Questions