14
votes

Scenario

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.

Problem

We use Router.replace('/') to reload the page. But it triggers a server-side rendering.

Question

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?

4
You can use this handy module github.com/shdnx/next-express - lakshman.pasala
We are using pure next.js now. Have not introduced express yet. - Jim Jin
getInitialProps can only be called on server side render, you can always call componentDidMount on the client - Agney
Nope. "getInitialProps" can be called in the client-side. - Jim Jin

4 Answers

14
votes

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

10
votes

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);
3
votes

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/

2
votes

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.logs 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: