T
TanStack3y ago
deep-jade

Change the react router example on github TanStack/query

I'm learning react-query/react-router reproducing this official example at the repo path: examples/react/react-router/src/routes/contact.jsx
But I don't understand some logic on how it works and I would like to ask for an opinion. Since the router loader is for accessing the data we fetch from the db, why fetch them outside the loader with
const { data: contact } = useQuery(contactDetailQuery(params.contactId)); inside the Contact component ? Isn't it more correct to use it inside the loader and then return this value with useLoaderData() ? Furthermore, could i use *ensureQueryData() *instead of the actual loader return value ? So I'd like to know if it is possible to change the loader in this way (with the backticked parts I removed): THE CODE:
import { useParams, useLoaderData } from 'react-router-dom';
...
export const loader =
(queryClient) =>
async ({ params }) => {
const query = contactDetailQuery(params.contactId);

`return (
queryClient.getQueryData(query.queryKey) ??
(await queryClient.fetchQuery(query))
);`
return ( await queryClient.ensureQueryData(query) );

};

...

export default function Contact() {
const params = useParams();

`const { data: contact } = useQuery(contactDetailQuery(params.contactId));`
const { data: contact } = useLoaderData();

return (
...
);
}
import { useParams, useLoaderData } from 'react-router-dom';
...
export const loader =
(queryClient) =>
async ({ params }) => {
const query = contactDetailQuery(params.contactId);

`return (
queryClient.getQueryData(query.queryKey) ??
(await queryClient.fetchQuery(query))
);`
return ( await queryClient.ensureQueryData(query) );

};

...

export default function Contact() {
const params = useParams();

`const { data: contact } = useQuery(contactDetailQuery(params.contactId));`
const { data: contact } = useLoaderData();

return (
...
);
}
1 Reply
absent-sapphire
absent-sapphire3y ago
For ensureQueryData there is a paragraph here mentioning that it's equivalent: https://tkdodo.eu/blog/react-query-meets-react-router#getquerydata--fetchquery
React Query meets React Router
React Query and React Router are a match made in heaven.

Did you find this page helpful?