Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reload Next.js page initial props without reloading the whole page

I have a Next.js page that fetches data in the getInitialProps function and I want to reload this data from the browser without reloading the page, which would be unperformant and lose the user's scroll position. Is there some way to reload the initial props without reloading the entire page?

like image 550
Robert Moore Avatar asked Oct 17 '25 13:10

Robert Moore


1 Answers

This can be done by calling router.replace:

import { useRouter } from 'next/router';

function YourPage({ someProps }) {
  const router = useRouter();

  // Call this function when you want to refresh the data
  const refreshData = () => router.replace(router.asPath);

  // Your JSX
}

router.replace is a method to update the URL without adding a new entry to the history. router.asPath is the current URL. So it's like doing a client-side redirect to the same page, and client-side redirects re-fetch the props.

The answer above won't work, I don't believe, since functions can't be serialized and sent from server to client.

like image 176
Joshua Comeau Avatar answered Oct 19 '25 09:10

Joshua Comeau