While working on an example for pagination with useInfiniteQuery() I have stumbled on the following error:
Uncaught Error: No QueryClient set, use QueryClientProvider to set one
My initial code was looking like this:
/* ⛔️ getting the following error on this code:
No QueryClient set, use QueryClientProvider to set one */
const App = () => {
const {isLoading, error, data} = useQuery({
queryKey: ['usersData'],
queryFn: () =>
fetch('https://randomuser.me/api').then(res => res.json()),
});
if (isLoading) return '⏳ loading...';
if (error) return 'An error has occurred!';
return (<div>
{data.results.map(user => (
<div key={user.id.value}>
👨💻 User: {user.name.first} {user.name.last}
</div>
))}
</div>);
}
After some research, I've discovered that in order to get the ReactQuery to work I need to do the following:
- create a new QueryClient
- extract the part that uses the ReactQuery useQuery() hook into its own component
- finally, wrap my component in a QueryClientProvider using the newly created QueryClient
Below is how the code should have looked like:
// ❶ make a new queryClient
const queryClient = new QueryClient();
// ❷ extract the useQuery() part in its own component
const Results = () => {
const {isLoading, error, data} = useQuery({
queryKey: ['usersData'],
queryFn: () =>
fetch('https://randomuser.me/api').then(res => res.json()),
});
if (isLoading) return '⏳ loading...';
if (error) return 'An error has occurred!';
return (<div>
{data.results.map(user => (
<div key={user.id.value}>
👨💻 User: {user.name.first} {user.name.last}
</div>
))}
</div>);
}
// ❸ wrap the component in a QueryClientProvider
const App = () => (
<QueryClientProvider client={queryClient}>
<Results />
</QueryClientProvider>
)
You can see the working example on GitHub pages and the full code in the repo.
📖 50 Javascript, React and NextJs Projects
Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.
📖 50 Javascript, React and NextJs Projects
Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.