Having the following hook:
import { useQuery } from 'react-query';
import axios from 'axios';
export const useGetData = () => {
const query = 'getData';
const { isLoading, isError, data, error, refetch, isSuccess } = useQuery(
query,
async () => {
const { data } = await axios(
'https://api.chucknorris.io/jokes/random'
);
return data;
}
);
return {
data,
isError,
isLoading,
error,
refetch,
isSuccess,
};
};
export default useGetData;
For the beginning, I want to import it into a component and check the values of data
, isError
and others.
Here is the component:
import React from 'react';
import { QueryClient, QueryClientProvider } from 'react-query';
import useGetData from './components/use-get-data';
const queryClient = new QueryClient({});
function App() {
const { data, isLoading } = useGetData();
console.log('data: ', data);
console.log('isLoading: ', isLoading);
return (
<QueryClientProvider client={queryClient}>
<div className='container'></div>
</QueryClientProvider>
);
}
export default App;
It throws the following error:
Uncaught Error: No QueryClient set, use QueryClientProvider to set one
at useQueryClient
How can this be fixed?
CodePudding user response:
Your call to your hook need to be under the query client provider to access his context. So you need to put it in a component called as a child of QueryClientProvider
CodePudding user response:
You should put the useGetData
custom hook in the descendants component of the QueryClientProvider
provider so that you can use useQuery
hook.
Because useQuery
hook use useQueryClient
hook underly, see source code, and useQueryClient
use useContext
hook underly, source code:
export const useQueryClient = () => {
const queryClient = React.useContext(
getQueryClientContext(React.useContext(QueryClientSharingContext))
)
if (!queryClient) {
throw new Error('No QueryClient set, use QueryClientProvider to set one')
}
return queryClient
}
queryClient
context comes from QueryClientProvider
so that useContext
can get it.