In React JS useQuery
and useQueries
are two different hooks that serve distinct purposes when for fetching and managing data.
useQuery
:
useQuery
is used to fetch and manage data for a single query.- It takes a single query key as its primary argument and an optional configuration object.
- You use
useQuery
when you want to fetch data for a specific resource or endpoint. - It automatically manages caching, fetching, and re-fetching based on your configuration settings.
Below is an example of useQuery: (Where url is dam json path)
import {useQuery} from "@transtack/react-query";
export default function ReadData{
let url = "/content/dam/myproject/profile.json";
let {data, error, isError, isLoading, isState, ...otherParams} = useQuery (
[url],
fetchUrlSynchronously
);
if (isLoading) {
return <div>Loading...</div>;
}
if (error) {
return <div>Error: {error.message}</div>;
}
return (
<div>
{/* Display data */}
</div>
);
}
useQueries
:
useQueries
is used to fetch multiple queries simultaneously.- It takes an array of query objects as its primary argument. Each query object includes a query key and a fetching function.
- You use
useQueries
when you need to fetch data for multiple resources or endpoints in parallel. - It returns an array of query result objects, each containing data, loading status, and errors for the corresponding query.
Below is an example of useQueries:
import {useQueries} from "@transtack/react-query";
export default function ReadData{
const urls = [
{ url: 'content/dam/myproject/profileOne.json' },
{ url: '/content/dam/myproject/profileTwo.json' }
];
let {data, error, isError, isLoading, isState, ...otherParams} = useQuery (
[url],
fetchUrlSynchronously
);
let queryResults: any []= useQueries({
queries: Object.keys(urls).map((key) => {
return {
queryKey: [urls[key].url],
queryFn: fetchUrlAsynchronously,
...{ enabled: true}
}
})
});
return (
<div>
{queryResults.map((result, index) => (
<div key={index}>
{result.isLoading ? 'Loading...' : null}
{result.error ? `Error: ${result.error.message}` : null}
{result.data ? /* Display data */ : null}
</div>
))}
</div>
);
}
In summary, the key difference lies in the purpose and scope of these hooks. useQuery
is for fetching data for a single query, while useQueries
is for handling multiple queries concurrently. Depending on your use case, you can choose the hook that best fits your requirements. React Query’s documentation provides comprehensive information on both hooks and how to configure them for optimal use.
Thank you for reading.
Happy Coding!