Browser back button using Nextjs refresh the component after a few seconds

325 views Asked by At

I'm using React and Next.js in this project, I have a list of products that I get from a query in one batch and display 15 at a time. I manage this using the parameter p, for pages. So every time I load another page, param p changes its number.

The problem is that when the user clicks on browser back button, the products change (as they should), but after a few seconds I get a full refresh of the page.

Here is how I do the params change:

useEffect(() => {
  if (typeof window != "undefined" && router.isReady) {
    router.push(
      {
        pathName: window.location.pathname,
        query: { ...router.query, p: page }
      },
      null,
      { shallow: true });
  }
}, [page]);

I tried router.beforePopState but I can't prevent page from refreshing. I also tried:

window.addEventListener('beforeunload', (event) => {
  event.preventDefault()
});

Which helps since it doesn't reload the page (it doesn't make any change, but I can solve this problem), the issue here is the browser shows two alerts...

I need one of two things:

  • The page doesn't refresh and the products are correctly shown (as it happens now, but then it reload the page)
  • Or the page does the reload, but without showing the change of products before the reload.
0

There are 0 answers