I am developing a react-redux application where once the user logs in, I was to store some information about the user in local storage. This is so that I can easily retrieve the user information when they perform a action.
If the user close the browser window, I would like to clear all localstorage for the react application. How can I achieve that?
How to delete a localStorage item when the browser window/tab is closed? To clear a localStorage data on browser close, you can use the window.onunload event to check for tab close. Let's say you have a local storage object called MyStorage as a global for the sake of this example. Then you can write an event handler −
LocalStorage in ReactJS 1 Syntax. 2 Set, retrieve and remove data in localStorage. In this example, we will build a React application which takes the... 3 Example. In the above example, when the Done button is clicked, the handle function is executed which will set the items... 4 Output. This will produce the following result. More ...
LocalStorage is a web storage object to store the data on the user’s computer locally, which means the stored data is saved across browser sessions and the data stored has no expiration time.
You can just use the JS function : localStorage.clear(); Firing the event on close of the window window.onbeforeunload = function() { localStorage.clear(); } Share Follow edited Dec 27 '17 at 2:58
You can just use the JS function :
localStorage.clear();
Firing the event on close of the window
window.onbeforeunload = function() {
localStorage.clear();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With