Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Next.js - execute callback when Router.push() or getInitialProps() completes

I have a page that generates a random number in getInitialProps() after 2 seconds. There's a button that allows the user to "refresh" the page via Router.push(). As getInitalProps() takes 2 seconds to complete, I'll like to display a loading indicator.

import React from 'react'
import Router from 'next/router'

export default class extends React.Component {
  state = {
    loading: false
  }

  static getInitialProps (context) {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        resolve({random: Math.random()})
      }, 2000)
    })
  }

  render() {
    return <div>
      {
        this.state.loading
        ? <div>Loading</div>
        : <div>Your random number is {this.props.random}</div>
      }
      <button onClick={() => {
        this.setState({loading: true})
        Router.push({pathname: Router.pathname})
      }}>Refresh</button>
    </div>
  }
}

How can I know when Router.push()/getInitialProps() completes so I can clear my loading indicator?

Edit: Using Router.on('routeChangeComplete') is the most obvious solution. However, there are multiple pages and the user could click on the button multiple times. Is there a safe way to use Router events for this?

like image 342
nwarp Avatar asked Jul 12 '26 12:07

nwarp


1 Answers

Router.push() returns a Promise. So you can do something like...

Router.push("/off-cliff").then(() => {
  // fly like an eagle, 'til I'm free
})
like image 99
jchi2241 Avatar answered Jul 14 '26 04:07

jchi2241



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!