0

I want to cancel componentWillUnmount() method if data is not saved.I have state property IsSaved which defines whether data is saved or not? I want to write something like componentWillUnmount() { if(!IsSaved) { //Cancel unmount stay on same component } } Is this possible? Or I need to achieve it by some other way?

KRN
  • 11
  • 1
  • Hey KRN! Welcome to SO. Check out this post, I think its a similar one to the one you're asking here (So long as you're using react-router?) https://stackoverflow.com/questions/41509898/cancel-componentwillunmount-if-a-form-is-incomplete – lsimonetti Sep 17 '18 at 15:27
  • You can't you will need to remount the component if you need to on failure (from the parent) – Dominic Sep 17 '18 at 15:28
  • hello, could you please elaborate more? what is the actual condition in which isSaved == false? – Charlie Sep 17 '18 at 15:28
  • IsSaved is false intially when my component opens in edit mode. On Save button click Im setting IsSaved to true. In case any change happens again I set it as false. Now there are many navigation links in top bar and side bar, if user clicks on those links I want to show popup to confirm that user wants redirect and his changes will be lost. – KRN Sep 17 '18 at 15:39

1 Answers1

0

You cant cancel "componentWillMount" as it is a lifecycle callback. What you CAN do is to avoid component unmounting. So if you can prevent to propagate an action that will cause the unmount of a component, this is the right approach to your problem in react.

NOTE:

If the component unmount is triggered by react-router you can try setRouteLeaveHook

componentWillMount() {
    this.unregisterLeaveHook = props.router.setRouteLeaveHook(props.route, this.routerWillLeave.bind(this));
}

routerWillLeave(nextLocation) {
  return false;        
}

And when you want to unmount component unregister the hook:

componentWillUnmount() {
    this.unregisterLeaveHook();
}

ref: How can I prevent the unmount in React Components?

Mosè Raguzzini
  • 15,399
  • 1
  • 31
  • 43