Using ReactQuery with React instead of Axios + hooks
In your React app you can use ReactQuery and ReactQueries for request caching, background updates and stale data out of the box with zero-configuration, instead of just Axios + hooks.
UseQuery : 1 api request
import { useQuery } from '@tanstack/react-query';
import axios from 'axios';
...
const getServices = () => {
return axios.get('https://jsonplaceholder.typicode.com/posts');
};
...
const { data, isError, isLoading } = useQuery(['services'], getServices);
if (isLoading) {
return <p>Loading...</p>;
}
if (isError) {
console.error('error');
}
return <ServiceComponent data={data} />;
UseQueries : 2+ api request
Index.tsx
import { useQueries } from '@tanstack/react-query';
import axios from 'axios';
...
const getServiceOne = () => {
return axios.get('https://jsonplaceholder.typicode.com/posts');
};
...
const results: any = useQueries({
queries: [
{ queryKey: ['serviceOne'], queryFn: getServiceOne, staleTime: Infinity },
{ queryKey: ['serviceTwo'], queryFn: getServiceTwo, staleTime: Infinity },
],
});
const serviceOneResult = results[0];
const serviceTwoResult = results[1];
const isError = serviceOneResult.error || serviceTwoResult.error;
const isLoading = serviceOneResult.isLoading || serviceTwoResult.isLoading;
if (isLoading) {
return <p>Loading...</p>;
}
if (isError) {
console.error('error');
}
return (
<ServiceComponent
dataOne={serviceOneResult.data}
dataTwo={serviceTwoResult.data}
/>
);