#Problem with react-query and dynamic routing

1 messages · Page 1 of 1 (latest)

prime saffron
#

I have a Nextjs app witf 2 static routes, respectively locations and characters. Inside this you can find links that redirect to 2 dynamic routes, location/[lid] and character/[cid].

In my project I am using tanstack useQuery

Here's my problem: if I access character/[cid] first, and then navigate through the app and access location/[lid], the second page's useQuery data object will be the same that was fetched in the first page. This is causing some errors in my application, beacuse I'm trying to access properties that are not actually there

outer gardenBOT
#

Hi @prime saffron. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

Hmm, I don't know enough to give you a confident answer yet. However, I can provide some general guidance based on the information extracts.

When fetching data in Next.js, it's important to ensure that you're fetching the correct data for each route. Next.js automatically deduplicates fetch requests for the same data across different components, such as generateMetadata, generateStaticParams, Layouts, Pages, and Server Components source (https://nextjs.org/docs/app/api-reference/functions/generate-static-params).

To avoid issues with data fetching, consider the following:

  1. Fetch data directly inside the layout or component that needs it, even if you're requesting the same data multiple times in a route. React and Next.js will cache and dedupe requests to avoid fetching the same data more than once source (https://nextjs.org/docs/app/building-your-application/data-fetching).

  2. Move data fetching lower in the component tree to only block rendering for the parts of the page that need it. This allows you to show a loading state for only the part of the page that is loading, and not the entire page source (https://nextjs.org/docs/app/building-your-application/data-fetching/fetching).

  3. When linking to dynamic routes, make sure you're using the correct path and query parameters. You can use interpolation or a URL object to create the path for dynamic route segments source (https://nextjs.org/docs/pages/building-your-application/routing/linking-and-navigating).

For more information on data fetching in Next.js, you can refer to the Data Fetching documentation (https://nextjs.org/docs/app/building-your-application/data-fetching).

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: