Revalidate Router Cache on browser 'back'
Unanswered
Barbary Lion posted this in #help-forum
Barbary LionOP
I want to revalidate a router cache when a user calls the
Problem
On the main page of my app
I'm assuming this is due to Next's soft navigation?
Using Next 13 (app router).
Has anyone else come across this?
back() function via the browser button, as the app shows stale data.Problem
On the main page of my app
/ I have a list of items loaded via a server component doing an async prisma.find. On another page /create, a user can create a new list item via a API request to a Route Handler. In the Route Handler I call revalidatePath("/") to revalidate the cache on the next visit to /. This works if the user navigates to / via a Link, and I see the new list item as the cache was revalidated, however this is not the case when using the browser back button, going from /create to /. I only see stale data.I'm assuming this is due to Next's soft navigation?
Using Next 13 (app router).
Has anyone else come across this?
2 Replies
Barbary LionOP
I've tried intercepting the browser event via 'popstate', but
window.history.state is always null - again assuming because all the nav is done via Next's soft navigation, so the browser history isn't poplated?Barbary LionOP
I've found a workaround but it feels a bit illegal:
🤷
/create: useEffect(() => {
// other stuff
// hook into component unmount
return () => {
// custom zustand store
setPreviousPathname("/create");
};
}, [chat, setPreviousPathname]);/layout.tsx:<body>
<NavigationEvents>
{children}
</NavigationEvents>
</body>NavigationEvents.tsx: useEffect(() => {
window.addEventListener("popstate", (event) => {
const pathname = window.location.pathname;
if (pathname === "/" && previousPathname === "/create") {
router.refresh();
}
});
}, [previousPathname, router]);🤷