How can I prevent componentWillUnMpunt()?

Hi Campers!

implementing a prompt (Stay on Page - Leave) in React, I taught that the hook componentWillUnMount() is the ideal case to put the prompt as it detects all the various way the component will be un mounted , here is the problem … I didn’t get routers in the props and hence I don’t know when the user clicks Stay on Page to actually stay on page…
any ideas will be appreciated !
Thanks

in React, I taught that the hook componentWillUnMount() is the ideal case to put the prompt as it detects all the various way the component will be un mounted

If I understand you, you are misunderstanding componentWillUnmount(). That is called by React just before your component unmounts. You don’t put things in there that will cause your component to unmount. You put things in there that you want to happen before you unmount. For example if you had some timers that you wanted to clear or if you wanted to make sure your database was in a good state before you left. It is used for cleanup. Most of the time you don’t need it.

If you want a “prompt” like a button to go somewhere else, then just have the navigation action or the anchor on that button. React will automatically call CWUM and if you have any cleanup work you need, that is where you would put it.

@kevinSmith sorry for my late replay .

I get your point and now using react-router hooks onLeave , what I’m missing is that when the user clicks Stay on Page How can I prevent the routing and stay on the same page with same state ?

Thanks!

Sorry, I think I’m going to have to see a repo to understand what you are trying to do.

@kevinSmith
<Route path="student/:id" onLeave={myFunction}/>

const myFunction = () => { //show prompt with string like are u sure you want to leave //in case user click yes -> ok the route will be executed and the page will be left //otherwise user click cancel .. how to prevent navigation to the specific path }

IC, I think I get it now. I’ll try to take a look when I get home tonight.

But do you have a repo for this? So I don’t have to recreate all this from scratch?

unfortunately I don’t . :frowning:

Rather than retype it out, this sounds like what you want.