0

Our application is developed using react and on refreshing and route navigation, we need to check for unsaved changes in the page and show an alert. For this scenario, we were able to leverage with route API on page-navigation, and yet refreshing the page directly seems not working.

Mukundhan
  • 3,284
  • 23
  • 36

2 Answers2

1

So in your case basically a user has typed a long form, so there are below cases you need to show him the message that unsaved changes will be lost.

  1. When switching to different component clicking on any of the link
  2. Refreshing the component

So inorder to do these there is a native event called beforeunload, so you need to add the event to the document by using document.addEventListener in componentDidMount and you can unmount that one in componentWillUnmount in the parent component

so there should be check to know the form has been dirty which means user has typed something, like isDirty in redux-form.

so whenever the user is typing something you can make this value to true based on this value if the user clicks on the refresh you can have the check and execute it

You can check more on here and this

so you can hold a state variable at the parent level and based on this you can trigger it

Learner
  • 8,379
  • 7
  • 44
  • 82
0

You can use Promise struct and run your refresh other whatever if you want in then

export const unSavedChanges= (values,listTitle)=>    new Promise((resolve, reject) => {
//Your code of check, validation what ever
})

when you call this func

unSavedChanges(changes,"list").then(response=>{
refresh.page
}
)