Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing react-router browserHistory change listener

I've a react component that listens to route changes using browserHistory's listen method. After registering a handler with

browserHistory.listen(this.handleRouteChanged)

in ComponentDidMount, how do I remove the listener in componentWillUnmount?

I can't find any documentation on this, and searching through github issues I've found suggestions using browserHistory.unregisterTransitionHook which doesn't seem to remove the listener, and in addition seems to be deprecated.

Any ideas?

like image 351
jul Avatar asked Jun 20 '16 11:06

jul


1 Answers

The listen() method returns a function that will stop it from listening. This is documented on the history docs:

A "history" encapsulates navigation between different screens in your app, and notifies listeners when the current screen changes.

import { createHistory } from 'history'

const history = createHistory()

// Get the current location 
const location = history.getCurrentLocation()

// Listen for changes to the current location 
const unlisten = history.listen(location => {
  console.log(location.pathname)
})

// Push a new entry onto the history stack 
history.push({
  pathname: '/the/path',
  search: '?a=query',

  // Extra location-specific state may be kept in session 
  // storage instead of in the URL query string! 
  state: { the: 'state' }
})

// When you're finished, stop the listener 
unlisten()
like image 62
Chris Avatar answered Oct 17 '22 00:10

Chris