How to tackle No QueryClient set, use QueryClientProvider to set one in React Query v3

Viewed 4229

My code looks like this :

import { useQuery, QueryClientProvider, QueryClient } from 'react-query'
import React from 'react'

const queryClient = new QueryClient()

const fetchData = async () => {
  return (await fetch(`http://jservice.io/api/random?count=50`)).json()
}

function App() {

  const [isLoading, error, data] = useQuery('qa', fetchData)

  console.log(data)


  return (

    <QueryClientProvider client={queryClient}>
      <div className="App">
      </div>
    </QueryClientProvider>

  );
}

export default App;

I have used the exact example from React Query v3 and still get

Error: No QueryClient set, use QueryClientProvider to set one

I am at the verge of giving up the library altogether and resort to alternatives.

2 Answers

Put QueryClientProvider at the root of your react app.

I guess in index file.

At the time function tries to run hook useQuery hook query client cache is not initialized and that will trigger that error.

If you don't want to keep that in index at least it should be in the parent function not in the same from where you are using useQuery, useMutation or any hook.

I found this from their official documentation on using the Query Client, just go to your root file, maybe App.js or Index.js and wrap it up with the

     <QueryClientProvider client={queryClient}>
       <Todos />
     </QueryClientProvider>
import {
  useQuery,
  useMutation,
  useQueryClient,
  QueryClient,
  QueryClientProvider,
} from 'react-query'
import { getTodos, postTodo } from '../my-api'

// Create a client
const queryClient = new QueryClient()

function App() {
  return (
    // Provide the client to your App
    <QueryClientProvider client={queryClient}>
      <Todos />
    </QueryClientProvider>
  )
}

function Todos() {
  // Access the client
  const queryClient = useQueryClient()

  // Queries
  const query = useQuery('todos', getTodos)

  // Mutations
  const mutation = useMutation(postTodo, {
    onSuccess: () => {
      // Invalidate and refetch
      queryClient.invalidateQueries('todos')
    },
  })

  return (
    <div>
      <ul>
        {query.data.map(todo => (
          <li key={todo.id}>{todo.title}</li>
        ))}
      </ul>

      <button
        onClick={() => {
          mutation.mutate({
            id: Date.now(),
            title: 'Do Laundry',
          })
        }}
      >
        Add Todo
      </button>
    </div>
  )
}

render(<App />, document.getElementById('root'))
Related