Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

No QueryClient set, use QueryClientProvider to set one

I was trying to react query for the first time then I got this at the start of my React app. enter image description here

import React from 'react'
import { useQuery } from "react-query";

const fetchPanets = async () => {
    const result = await fetch('https://swapi.dev/api/people')
    return result.json()
}

const Planets = () => {
    const { data, status } = useQuery('Planets', fetchPanets)
    console.log("data", data, "status", status)
    return (
        <div>
            <h2>Planets</h2>
        </div>
    )
}

export default Planets
like image 510
unsuredev Avatar asked Jan 06 '21 04:01

unsuredev


People also ask

What is Usemutation in react query?

A function that performs an asynchronous task and returns a promise. variables is an object that mutate will pass to your mutationFn.

How do I get error message in react query?

For React Query to determine a query has errored, the query function must throw. Any error that is thrown in the query function will be persisted on the error state of the query. throw new Error('Oh no! ')

Can I use react query with Firebase?

React Query Firebase provides a set of easy to use hooks for common Firebase usecases. Each hook wraps around React Query, allowing to easily integrate the hooks into a new or existing project, whilst enjoying the powerful benefits React Query offers.

What is useQueryClient?

The useQueryClient hook (to not be confused with the useQuery hook or QueryClient ) is our entry point to interacting with our query cache. The useQueryClient hook returns the instance of the current QueryClient of our application.

What is “no queryclient set” error in react-query?

There is a common error called “No QueryClient set, use QueryClientProvider to set one” of react-query that most newbies found complicated, so in this tutorial, I am going to show to how to fix this error. Let solve this together!

Why is my queryclient () not working?

While this is most commonly caused by not having your application wrapped in a <QueryClientProvider>, in my case it happened because I was importing some shared components, which ended up with a different context. You can fix this by setting the contextSharing option to true

What is the use of queryclient?

QueryClient The QueryClient can be used to interact with a cache: QueryClient The QueryClient can be used to interact with a cache: Looking for theReact Query v3 documentation?

How do I remove a query from queryclient cache?

queryClient.removeQueries The removeQueriesmethod can be used to remove queries from the cache based on their query keys or any other functionally accessible property/state of the query. tsx queryClient.removeQueries(queryKey,{exact:true})


5 Answers

As the error suggests, you need to wrap your application in a QueryClientProvider. This is on the first page of the docs:

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

const queryClient = new QueryClient()

export default function App() {
   return (
     <QueryClientProvider client={queryClient}>
       <Example />
     </QueryClientProvider>
   )
}
like image 50
TkDodo Avatar answered Oct 20 '22 19:10

TkDodo


While this is most commonly caused by not having your application wrapped in a <QueryClientProvider>, in my case it happened because I was importing some shared components, which ended up with a different context. You can fix this by setting the contextSharing option to true

That would look like:

 import { QueryClient, QueryClientProvider } from 'react-query'
 
 const queryClient = new QueryClient()
 
 function App() {
   return <QueryClientProvider client={queryClient} contextSharing={true}>...</QueryClientProvider>
 }

From the docs: (https://react-query.tanstack.com/reference/QueryClientProvider)

contextSharing: boolean (defaults to false)

Set this to true to enable context sharing, which will share the first and at least one instance of the context across the window to ensure that if React Query is used across different bundles or microfrontends they will all use the same instance of context, regardless of module scoping.

like image 43
Fred Antell Avatar answered Oct 20 '22 18:10

Fred Antell


Just make changes like below it will work fine

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import { QueryClient, QueryClientProvider } from "react-query";
const queryClient = new QueryClient();

ReactDOM.render(
  <QueryClientProvider client={queryClient}>
    <App />
  </QueryClientProvider>,
  document.getElementById('root')
);
like image 6
Rocky Avatar answered Oct 20 '22 20:10

Rocky


import {  QueryClient, QueryClientProvider, useQuery } from 'react-query';
const queryClient = new QueryClient();
const fetchPanets = async () => {
    const result = await fetch('https://swapi.dev/api/people')
    return result.json()
}

const Planets = () => {
    const { data, status } = useQuery('Planets', fetchPanets)
    console.log("data", data, "status", status)
    return (
        <div>
            <h2>Planets</h2>
        </div>
    );
}


export default function Wraped(){
return(<QueryClientProvider client={queryClient}>
        <Planets/>
    </QueryClientProvider>
);
    
}
like image 5
Kim Aguilar Avatar answered Oct 20 '22 19:10

Kim Aguilar


I was trying to fix the same thing:

I followed the React Query docs and used the concept of Higher Order Component

See if it helps:
import React from 'react';
import { QueryClient, QueryClientProvider, useQuery } from 'react-query';

import Planet from './Planet';

const queryClient = new QueryClient();

const fetchPlanets = async () => {
    const res = await fetch('http://swapi.dev/api/planets/');
    return res.json();
}

const Planets = () => {

    const { data, status } = useQuery('planets', fetchPlanets);

    return (
        <div>
            <h2>Planets</h2>
            { status === 'loading' && (<div>Loading data...</div>)}
            { status === 'error' && (<div>Error fetching data</div>)}
            {
                status === 'success' && (
                    data.results.map(planet =>
                        <Planet
                            key={planet.name}
                            planet={planet}
                        />
                    )
                )
            }
        </div>
    )
}

// Higher order function
const hof = (WrappedComponent) => {
    // Its job is to return a react component warpping the baby component
    return (props) => (
        <QueryClientProvider client={queryClient}>
            <WrappedComponent {...props} />
        </QueryClientProvider>
    );
};

export default hof(Planets);
like image 2
smallfoxy Avatar answered Oct 20 '22 19:10

smallfoxy