TanStackT
TanStack3y ago
1 reply
nursing-lime

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 (
    ...
  );
}
Was this page helpful?