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?
Router.push() returns a Promise. So you can do something like...
Router.push("/off-cliff").then(() => {
// fly like an eagle, 'til I'm free
})
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