React Query - unable to access the data via 'getQueryData', always returns undefined

Viewed 3377

I am trying out React Query for the first time and I wrote this:

export function Component(): JSX.Element {
  const queryClient = new QueryClient()

  const { data } = useQuery<DataType>({
    queryKey: "myKey",
    queryFn: () => ....,
  })

  const sameData: DataType| undefined = queryClient.getQueryData("myKey")

  return (
    <>
      {console.log(data)}
      {console.log(sameData)}
      <p>Loaded, see console for values.</p>
    </>
  )
}

The data object is created as expected, but I cannot seem to make sameData return anything other than undefined. I know this means that React Query isn't finding my key. Does anyone have any ideas on how to fix this?

2 Answers

You’re creating a new QueryClient in each render, so you’ll get a new cache. Have a look at the example on the front page of the docs: https://react-query.tanstack.com/overview

You need a stable queryClient, and put it in a QueryClientProvider

like the above answer explained

const queryClient = new QueryClient() 

will create a new instance on every render

the provided useQueryClient() hook returns the current instance

const queryClient = useQueryClient()
Related