manish keer manish keer - 3 months ago 84
React JSX Question

Getting an error on using setRouteLeaveHook (withRouter)

Currently I'm building a Web App using ReactJS. The app has a registration form.

Now consider, user has started with the registration process. But before submitting the form user leaves this registration page. At this point, say form contains unsaved data and I would like to display a confirmation message saying that Save Changes you have made before leaving this screen.

Below is my code to achieve this

componentDidMount () {
this.props.router.setRouteLeaveHook('/enterprise/enterprise-area/enterprise-details', this.routerWillLeave);
}

routerWillLeave(nextLocation) {
// return false to prevent a transition w/o prompting the user,
// or return a string to allow the user to decide:
if (true) {
return 'Your work is not saved! Are you sure you want to leave?';
}
}

export default withRouter(connect(
mapStateToProps,{
initializeVendorDetails
})(VendorRegistration));


I get the error shown below:

Uncaught TypeError: Cannot assign to read only property '__id__' of /enterprise/enterprise-area/enterprise-details


I went through official documentation and github issues but found nothing. Thanks in anticipation.

Answer

@NobuhitoKurose Thanks for your reply. Finally I manage to figure out the problem here.

Yes, My component was not directly connected to route.

I went through withRouter doc where I found that I actually need to provide a route object(this.props.route) as a first parameter instead of route as a string(as I mentioned in above code).

Since my component is not directly connected to route I was getting this.props.route as undefined.

I checked parent component (which is connected to route) and this component has its route prop. So I just pass this route prop from parent component to this current component (where I'm using withRouter) and everything has worked well.

Below is my an updated code

In parent component (which is connected to route)

<VendorRegistration route={this.props.route}/>

Component where I'm using withRouter

componentDidMount() {
    this.props.router.setRouteLeaveHook(this.props.route, this.routerWillLeave);
}

routerWillLeave(nextLocation) {
  // return false to prevent a transition w/o prompting the user,
  // or return a string to allow the user to decide:
  // FIXME: update condition as per requirement
  if (true) {
    return 'You have unsaved information, are you sure you want to leave this page?';
  }
}

export default withRouter(connect(
  mapStateToProps,{
  initializeVendorDetails
})(VendorRegistration));