How do I refresh the page in next.js 14 app router? #62146
-
Currently using next.js 14 app router. Modal window on the client-side (the page is the "/" page.) When logging in is completed. I would like to close the opened login modal window by refreshing the page. Currently, the router.refresh() method is used using useRouter, but the refresh itself does not work. What's the problem? I searched and found useRouter.
It says to use router.reload() after importing like this, but if you do this, the import itself will not work at all. How can I refresh the page after receiving data? - my code (use client)import { useRouter } from 'next/navigation';
const apiCallHandler = async () => {
const res = await fetch(fetch infos);
const data = await res.json();
if (success) {
await asyncFn();
router.refresh(); // it not works
}
}; I'm currently using window.location.reload() as a temporary measure, but I'm leaving a post because I don't think this is the normal method. |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 6 replies
-
It is perfectly fine to use As for the router.refresh method, let's look at the docs, https://nextjs.org/docs/app/api-reference/functions/use-router#userouter:
and from, https://nextjs.org/docs/app/building-your-application/caching#routerrefresh:
So while, perhaps the name is a bit mislead, it is far from a full page refresh method. The browser API already has a method for that. If you wanna take a deep dive into Caching and Revalidating in the App Router, check out this discussion thread: #54075 |
Beta Was this translation helpful? Give feedback.
-
This works for me! Make the route that needs a refresh an optional route parameter like below [[...slug]] refresh the page by navigating to the same route with a different refreshId import { useRouter } from 'next/navigation'; router.push(``/home?refreshId=${new Date().getTime()}`) |
Beta Was this translation helpful? Give feedback.
-
router.refresh works fine but you need invalidate the cache first. |
Beta Was this translation helpful? Give feedback.
It is perfectly fine to use
window.location.reload
.As for the router.refresh method, let's look at the docs, https://nextjs.org/docs/app/api-reference/functions/use-router#userouter:
and from, https://nextjs.org/docs/app/building-your-application/caching#routerrefresh: