Reputation: 9942
What I'm trying to do is detect when authentication changed (login/logout). My login form is in modal and there are some pages in my app that have minor differences when a user is logged in from when they're logged out. So I need to detect when that happens and refetch the pages' data to get updated information.
An example would be an Article
page. You can upvote the article but you have to be logged in.
Now whenever the authentication changes I write the token
and user
objects to localStorage. So I thought I would use the storage
event on the Article
component and listen to user
object change and refetch the data when it does change.
This is the code from my Article component that should detect the storage
change (removed irrelevant code):
class Article extends Component {
fetchData() {
// fetch data
}
componentDidMount() {
this.fetchData();
window.addEventListener('storage', function(e) {
console.log('storage fired');
// this.fetchData();
});
}
componentWillUnmount() {
// Remove event listener
}
render() {
return (
// Render article
);
}
}
The problem is that when I'm on this page and log in from my modal and write the changes to the storage
, the event doesn't fire. However, if I have another tab open on the same page, the event does fire there. So it works on all browser tabs, except the one where I'm actually logging in.
How would I go about solving this?
I'm also open to any other solutions to the problem. The problem being - detect an auth change and reload the page when it does change. I'm also writing the user and token objects to the redux store (if there's a nicer solution with redux maybe).
Edit:
I've recreated the issue with minimal code on this repository: https://github.com/d1am0nd/storage-problem
In order to run it, you have to start a local server in dist
folder (say localhost:3000). Then open 2 tabs and click the "Write to storage" button. An alert doesn't trigger on the current tab, but it does trigger on the other tab.
Upvotes: 0
Views: 1242
Reputation: 403
This is default behavior of this event.
A StorageEvent is sent to a window when a storage area it has access to is changed within the context of another document.
Look at: https://developer.mozilla.org/en-US/docs/Web/API/StorageEvent and https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API/Using_the_Web_Storage_API
Upvotes: 1