React: history.listen - How to unlisten?

Viewed 5785

On one module, I need to listen to the url change, so I wrote a simple code:

componentDidMount(){
        history.listen( location =>  {
            console.log('listen')
            doSomeStuff(location);
        });
    }

But after leaving the page where this module is used, I still see console.log('listen), it turns out that the listener still performs a function doSomeStuff(location), even where it is not necessary?

I read the documentation that says, quote:

"When you attach a listener using history.listen, it returns a function that can be used to remove the listener, which can then be invoked in cleanup logic:"

const unlisten = history.listen(myListener);
// ...
unlisten();

I do not understand what I need to write in ComponentWillUnmount to stop this listener.

I am using 2.8.0 version of react-router

1 Answers

you need to store the unlistener function in a variable in your class so you can call it from the other event

YourClass extends React {

  // ..
  componentDidMount() {
    this.unregisterHistoryListener = history.listen( location =>  {
      console.log('listen')
      doSomeStuff(location);
    });
  }

  componentWillUnmount(){
    this.unregisterHistoryListener()
  }
}
Related