简体   繁体   中英

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?

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

Router.push("/off-cliff").then(() => {
  // fly like an eagle, 'til I'm free
})

use can use Router event listener in pages/_app.js , manage page loading and inject state into component

import React from "react";
import App, { Container } from "next/app";
import Router from "next/router";

export default class MyApp extends App {
  state = {
    loading: false
  };

  componentDidMount(props) {
    Router.events.on("routeChangeStart", () => {
      this.setState({
        loading: true
      });
    });

    Router.events.on("routeChangeComplete", () => {
      this.setState({
        loading: false
      });
    });
  }

  static async getInitialProps({ Component, ctx }) {
    let pageProps = {};

    if (Component.getInitialProps) {
      pageProps = await Component.getInitialProps(ctx);
    }

    return { pageProps };
  }

  render() {
    const { Component, pageProps } = this.props;
    return (
      <Container>
        {/* {this.state.loading && <div>Loading</div>} */}
        <Component {...pageProps} loading={this.state.loading} />
      </Container>
    );
  }
}

and you can access loading as a props in your page component.

import React from "react";
import Router from "next/router";

export default class extends React.Component {
  static getInitialProps(context) {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        resolve({ random: Math.random() });
      }, 2000);
    });
  }

  render() {
    return (
      <div>
        {this.props.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>
    );
  }
}

you can also show loading text in _app.js (I've commented), that way you don't have to check loading state in every pages

If you wanna use third-party package here a good one nprogress

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM