How to get updated data from localStorage / sync tabs? #1614
-
How can I sync tabs while using I've already checked the "shared-zustand", but since I'm using Immer, it doesn't work: Tom-Julux/shared-zustand#4. Suppose I have a shopping cart. Currently, when I add something to it, the value in localStorage (say, I tried to solve this by watching for tab changes, and somehow "force-update" the state and make the component re-render. let bears = useStore((state) => state.bears);
useEffect(() => {
document.addEventListener("visibilitychange", getFreshDataFromStore)
return () => {
document.removeEventListener("visibilitychange", getFreshDataFromStore)
}
}, []);
const getFreshDataFromStore = () => {
// get updated "bears" from store, but hooks can't be used in functions
// I want to do `bears = useStore((state) => state.bears);` again
} However, I don't know how to get fresh data from the store. I know I might be doing some kind of anti-pattern here, but I'm really confused and need help! |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 5 replies
-
Hmm, I think BroadcastChannel is the right solution for syncing between tabs. If you want to refresh the store, you could use |
Beta Was this translation helpful? Give feedback.
-
Reading the docs again, I finally made it work: const updateStore = () => {
useStoreName.persist.rehydrate();
};
useEffect(() => {
document.addEventListener("visibilitychange", updateStore);
window.addEventListener("focus", updateStore);
return () => {
document.removeEventListener("visibilitychange", updateStore);
window.removeEventListener("focus", updateStore);
};
}, []); |
Beta Was this translation helpful? Give feedback.
Reading the docs again, I finally made it work: