šŸ“• LangChain for JavaScript developers is now out!
Build 5 Next.js apps with ChatGPT integrated features using LangChain.

Fixing the Uncaught Error: No QueryClient set, use QueryClientProvider to set one

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:

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.


Leave a Reply

Your email address will not be published. Required fields are marked *