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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With