Reputation: 495
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?
Upvotes: 14
Views: 46365
Reputation: 360
Took @BertC's answer but in the documentation there is a simpler way: react-beforeunload
npm i react-beforeunload
npm install @types/react-beforeunload --save-dev
in app.tsx
import { useBeforeunload } from 'react-beforeunload';
useBeforeunload(() => {
if (window) localStorage.clear();
});
Upvotes: 0
Reputation: 2656
You can make use of the NPM package react-beforeunload
On your main file (in NextJS world: _app.tsx) do the following:
...
import { Beforeunload } from 'react-beforeunload';
const removeApplicationData = () => {
if (window) { // NextJS is ServerSideRendering, therefore the window-check.
localStorage.clear();
}
};
...
return (
<Beforeunload onBeforeunload={removeApplicationData}>
<Component {...pageProps} />
</Beforeunload>
);
Upvotes: 1
Reputation: 738
To clear a localStorage
data on browser close, you can use the window.onunload
event to check for tab close.
window.onunload = () => {
// Clear the local storage
window.MyStorage.clear()
}
Upvotes: 1
Reputation: 73928
You could consider using Window.sessionStorage
instead of Window.localStorage
.
Data stored in sessionStorage gets cleared when the page session ends. A page
session lasts for as long as the browser is open and survives over page reloads. Source.
Upvotes: 8
Reputation: 15923
You can just use the JS function :
localStorage.clear();
Firing the event on close of the window
window.onbeforeunload = function() {
localStorage.clear();
}
Upvotes: 17
Reputation: 387
You can use localStorage.clear but you have to watch for window close event. Another possible solution is you can use session storage so it will be available until your browser is open. After that session will be removed, so you don't need to do anything.
Upvotes: 3