D
D
DanceMonkeyTime2020-06-24 21:29:13
JavaScript
DanceMonkeyTime, 2020-06-24 21:29:13

How to listen to browser back button and trigger actions (React + Next.js )?

I use React in conjunction with Next.js. There is a stepper, it is independent of the url, but depends on the store in the editor.
Now I am doing the functionality on the back button and the client wants it to be the same on both the custom button and the browser button.

The stepper is permanently on the /newurl.

I try to catch the desired action with the help of package history :

import Router from 'next/router';
import { createBrowserHistory } from 'history';

const history = createBrowserHistory();

history.listen((location) => {
    if (location.action === 'POP') {
        dispatch(updateScreenStep('back'));
        Router.push('/new'); // всегда обновляю урлу, что-бы не пошло дальше неё 
    }
  });


It works, but with errors if there is a large nesting of steps.
Perhaps someone has come across this?
How can this be implemented?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
H
hzzzzl, 2020-06-24
@hzzzzl

maybe it will come out stupidly in _app.js or put a popstate event handler in some main Layout.js wrapper?

React.useEffect(() => {
  window.addEventListener('popstate', doStuff)
  return () => {
    window.removeEventListener('popstate', doStuff)
  }
}, [doStuff])   // function doStuff() {}

But can I ask a question, how did redux hook up to the next one?
I didn’t try much, but it didn’t work out so that the store was not cleared after navigating between pages .. but I need it to be filled every time the page is loaded via getInitialProps, and therefore the page is re-rendered on the server every time

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question