React App Local Storage Is Not Setting Up
Solution 1:
I had trouble figuring what your codepen and the anotherPage function was trying to achieve, so I am providing you this codepen. Open it in two different windows and look at the shared number of notifications.
Please note that the suggested Local Storage solution is working only on the same browser as browsers does not share their Local Storages.
Here how to synchronize your Local Storage between two windows, without making any remote API call:
First let add an Event Listener. The first argument is the event type (here we are listening to storage), the second one is the callback. Note that listening to storage event works only between two windows (updating storage from a window will not trigger its own listener):
componentDidMount() {
window.addEventListener("storage", this.handleStorageUpdate);
}
Remember to remove this listener when you are not using it anymore (potentially on componentWillUnmount) to prevent any bloat.
componentWillUnmount() {
window.removeEventListener("storage", this.handleStorageUpdate);
}
Now let's take a look at our listener. It will receive all storage changes, but we only want to listen to the notifications changes. When the notifications changes in the storage, we want to update our component state to trigger a rerender with the new value:
handleStorageUpdate = storageChange => {
if (storageChange.key === "notifications") {
this.setState(() => ({ notifications: Number(storageChange.newValue) }));
}
};
So now, we are able to have two windows listening to the changes made by each others.
Let's just give a way to increase the amount of notification:
handleIncreaseNotification = () => {
const notifications = this.state.notifications + 1;
localStorage.setItem("notifications", notifications);
this.setState(() => ({ notifications }));
};
When increasing the number of notifications, you are setting the Local Storage item to be consumed by the other window. As you are not listening to your own changes of Local Storage, you need to set your state to this new number of notifications.
As you want to see the notification count directly when opening the window, remember to get the value of your Local Storage at one of the earliest state of your component lifecycle:
constructor(props) {
super(props);
const notifications = localStorage.getItem("notifications") || 0;
this.state = { notifications: Number(notifications) };
}
Finally you can render the entire component:
render() {
const { notifications } = this.state;
return (
<div>
<div> I have {notifications} notifications</div>
<button onClick={this.handleIncreaseNotification}>increase</button>
</div>
);
}
Post a Comment for "React App Local Storage Is Not Setting Up"