Next.js Discord

Discord Forum

Is there a better way to handle this?

Answered
Masai Lion posted this in #help-forum
Open in Discord
Avatar
Masai LionOP
I'm using router.refresh() after an API request.
The UX is not great because it has some dealy on it.
I want to improve the UX by getting the new data on the response and updating the content programmatically instead of refreshing the router to get a whole new page from the server, maybe even store the patient data on a useState().
Is there an easier/better way to fix the delay? I have this issue happening on multiple places on this project and I want to find the best solution so I can apply on all of them at once.
Thank you in advance!
Image
Answered by Hassib
Hi, I have done something like that in one of my projects. I used react-query for fetching requests. The react-query package has a function called invalidateQueries which automatically invalidates and fetches new results after for example the success of a request.

You can programmatically do something like this if you don't use react-query.

Note: I wouldn't recommend implementing the logic by yourself as it would take much more time and the maintenance would be harder. Use a library/package instead.

Take a look at this: https://tanstack.com/query/v4/docs/react/guides/query-invalidation
View full answer

7 Replies

Avatar
Hassib
Hi, I have done something like that in one of my projects. I used react-query for fetching requests. The react-query package has a function called invalidateQueries which automatically invalidates and fetches new results after for example the success of a request.

You can programmatically do something like this if you don't use react-query.

Note: I wouldn't recommend implementing the logic by yourself as it would take much more time and the maintenance would be harder. Use a library/package instead.

Take a look at this: https://tanstack.com/query/v4/docs/react/guides/query-invalidation
Answer
Avatar
Masai LionOP
Nice, that's what I was hoping for
Thank you
Avatar
Hassib
No worries
Please mark the question as answered if you don't mind 😊
Avatar
Masai LionOP
But what if I'm just fetching data using prisma on a server component? Do I need to change my code logic in order to make react-query work?
Avatar
Hassib
If the SEO is important and the application is not an Administration Panel, then do it in client components, if not, you can do it using the revalidation technique which is in Next.js. Next.js allows you to revalidate queries in two ways, time-based and on-demand revalidation.

Please check out this link: https://nextjs.org/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating#revalidating-data