I. Sep I. Sep - 3 months ago 33
Node.js Question

React Redux Confirming Navigation

I'm trying to achieve a product page, which gives the Administrator an ability to modify the product details by clicking an edit button, but if the Admin tries to leave the page with changes that they have not yet saved, it would confirm that the user wants to leave the page without saving.

Here is what I currently have in my ProductForm.js, which is used by Product.js when Admin clicks edit.

import { browserHistory } from 'react-router';
componentWillReceiveProps() {
browserHistory.listenBefore(location => {
console.log(location);
return 'Are you sure you want to leave the page without saving?';
});
}


The issue with the following code is that when the user opens the edit form, this confirmation message shows on every page transition, even if you're not on the product page.

I am using the following skeleton. https://github.com/erikras/react-redux-universal-hot-example

Answer

You can cancel listener like this:

import { browserHistory } from 'react-router';
  componentWillReceiveProps() {
    const cancelListner = browserHistory.listenBefore(location => {
      console.log(location);
      cancelListner();
      return 'Are you sure you want to leave the page without saving?';
    });
  }
Comments