simpler-state icon indicating copy to clipboard operation
simpler-state copied to clipboard

Create a plugin for syncing state across tabs

Open jalasem opened this issue 4 years ago • 4 comments

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

jalasem avatar Jun 25 '21 19:06 jalasem

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.

arnelenero avatar Jun 26 '21 15:06 arnelenero

Kindly guide me on how I can implement it. I don't mind publishing this as the first external plugin for simpler-state

jalasem avatar Jun 27 '21 16:06 jalasem

@arnelenero

jalasem avatar Jun 29 '21 06:06 jalasem

@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 set method (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 init method, 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 the entity.set to 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)

arnelenero avatar Jun 30 '21 14:06 arnelenero