简体   繁体   中英

Call an REST API before closing window (React)

I am creating a React App which creates a user when the user access the app and deletes that user from the database when the user closes the browser or reloads. For backend I have used Mongodb and Nodejs. I have tried using unload and beforeunload event listeners but it doesn't seem to work. Can someone help me

The best way you can do is to have a polling mechanism from the backend to check if the window is still open. Here are 2 solutions that I can think of:

  1. Make a websocket connection from the window to server. If the socket is closed => window is closed (Firebase uses this method for its onDisconnect )
  2. Use a setInterval to periodically send a ping (through REST API) to the backend. If the backend no longer receives ping, that means the window is closed.

Additionally, you can assign a random ID to each window. It will help to detect the case where users still open the window, but they lose connection.

React Client executes "componentWillUnmount" before exit. ALWAYS.

https://reactjs.org/docs/state-and-lifecycle.html

So call the server clean-up API there.


As Dan reminded me, this method is not reliable. The proper way to do this is to implement sessions on the node/express side with express-sessions, so once the user session expires, their entire user entry in the session storage is nuked.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM