How to get previous page url in nextjs

Viewed 2344

i created a _app.js file and added this code to it witch should store state of previous url in an array. When trying to access the previous url i just get the current page url.

Is there something wrong in the logic of the _app.js code or in passing the history value to other components/pages?

_app.js

import React from 'react';
import App from 'next/app';

class MyApp extends App {
  static async getInitialProps({ Component, ctx }) {
    let pageProps = {};

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

    return { pageProps };
  }

  state = {
    history: []
  };

  componentDidMount() {
    const { asPath } = this.props.router;

    this.setState(prevState => ({ history: [...prevState.history, asPath] }));

  }

  componentDidUpdate() {
    const { history } = this.state;
    const { asPath } = this.props.router;

    if (history[history.length - 1] !== asPath) {
      this.setState(prevState => ({ history: [...prevState.history, asPath] }));
    }
  }



  render() {
    const { Component, pageProps } = this.props
    return <Component history={this.state.history} {...pageProps} />
  }
}

export default MyApp;

Example of passing history

const CatPage = ({ history }) => {
  console.log(history) //I get the value of a current page 
  console.log(history[0]) // same thing it is just the current url in the array
}
0 Answers
Related