The index page uses "getInitialProps" to load data. Then we create a dialog which can create a new data. After creating a new data, the current page should be reloaded.
We use Router.replace('/')
to reload the page. But it triggers a server-side rendering.
What we need is a client-side reload. The "getInitialProps" function should be called in the browser. So, how to do the client-side reload?
In this article, we will learn about the Fast refresh in the NextJS project. Fast Refresh is a new hot reloading experience that gives you instantaneous feedback on edits made to your React components. It is now enabled by default for all projects on Next.
The Next. js router allows you to do client-side route transitions between pages, similar to a single-page application. A React component called Link is provided to do this client-side route transition.
By default, Next. js pre-renders every page. This means that Next. js generates HTML for each page in advance, instead of having it all done by client-side JavaScript.
Assume, a user is on the
http://www.example.com/profile
the user has edited the profile and for some reason, you need to reload the same page.
If your case is similar to this, you could use Router.reload();
Remember, you must import Router object like this import Router from "next/router";
For more information: https://nextjs.org/docs/api-reference/next/router#routerreload
Didn't see an answer that was really what I was looking for,
this worked for me:
import Router from 'next/router'
Router.reload(window.location.pathname);
A better option is to use router.replace(router.asPath)
replace does not create a new history item so Back button works as expected
Details explained in this article https://www.joshwcomeau.com/nextjs/refreshing-server-side-props/
Running the following code
pages/index.js
import Router from 'next/router';
function Index({ isServer }) {
console.log('render', new Date());
return (
<div>
<h1>Home page. Is it on server? - {isServer ? 'Yes' : 'No'}</h1>
<button type="button" onClick={() => Router.push('/')}>
Reload me
</button>
</div>
);
}
Index.getInitialProps = async ({ req }) => {
return { isServer: !!req };
};
export default Index;
I can see that it console.log
s render only once on the server even after clicking "Reload me". I can see that isServer
equals to false after "reload" as well.
How do you exactly reload the page so you see it is rendered on server side?
PS
Here are screenshots:
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