next-routes icon indicating copy to clipboard operation
next-routes copied to clipboard

Prevent page reload with browser back and forth buttons

Open vaibhav-kona opened this issue 5 years ago • 1 comments

I am using next-redux-wrapper and the redux state is getting lost because of the full page reloads happening when navigating using browser back and forth buttons. How to disable this and let client side routing take place instead of making server requests each time ?

vaibhav-kona avatar Dec 06 '18 13:12 vaibhav-kona

I ran into the same issue.

You may want to override next.js' App component and provide the Router that comes from next-routes, like so:

// pages/_app.tsx

import App, { Container, NextAppContext } from 'next/app';
import * as PropTypes from 'prop-types';
import React from 'react';

import { routes } from '../routes';

export default class CustomApp extends App {
  public static childContextTypes = {
    router: PropTypes.object,
  };

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

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

    return { pageProps };
  }

  public getChildContext() {
    return {
      router: routes.Router,
    };
  }

  public render() {
    const { Component, pageProps } = this.props;

    return (
      <Container>
        <Component {...pageProps} />
      </Container>
    );
  }
}

Keep in mind this is Typescript, so if you are writing in plain Javascript the syntax will be slightly different, but I hope you get the idea.

This makes it so that the page is not reloaded when using the browser's back and forward buttons. I am still having problems when the user manually edits the slug in url, though.

Gelio avatar Dec 08 '18 20:12 Gelio