Create a plugin for syncing state across tabs
Is your feature request related to a problem? Please describe. I'm currently using simpler-state in an enterprise project and I need to sync the tabs. For example, when a user logs out, I want him/her to be logged out on all tabs automatically.
Describe the solution you'd like I want every tab to receive an update when anything changes in the state
Describe alternatives you've considered Something like redux sync state
This is an interesting use-case. This can be something that could be built complementary to the persistence plug-in. But since even Redux Sync State uses a third-party BroadcastChannel (because official API is not yet widely standard on browsers), adding that 3rd party lib would in itself be 4x the size of simpler-state! This could be a good candidate for an "external" (not bundled) plug-in.
Kindly guide me on how I can implement it. I don't mind publishing this as the first external plugin for simpler-state
@arnelenero
@jalasem
My rough idea is:
- Use persistence plug-in on each entity that you wish synchronized
- Your tab sync plug-in will then implement an override for the
setmethod (see https://simpler-state.js.org/recipe-plugins.html) - In the override, you will have to use the BroadcastChannel (I haven't used that before, TBH) to send a message that the persisted (localStorage) value of your entity has changed (no need to send the actual value, since this is available on localStorage—just the "key" used for persistence will do).
- Your tab sync plug-in will also need to implement an override for the
initmethod, so that you can set a listener to the BroadcastChannel. Whenever the listener detects a message that the entity has changed on a different tab, it will need to get the new value from localStorage, then invoke theentity.setto sync this tab.
Something like that I think should work.
(Since BroadcastChannel is not yet supported by all browsers, you will need to use this instead: https://github.com/pubkey/broadcast-channel)