Search code examples
sveltesvelte-3svelte-component

Real-time data sharing in Svelte between unrelated components


I have a case where I have two tabs open localhost:5000/ and localhost:5000/stream and would like to update a variable in / path and see that change in stream path in real time. Store doesn't work like that, and if I use local storage with store, I get the data on stream page only after refreshing it, which is not what I need. Is there any solution for this?


Solution

  • There are two ways to do this:

    use localStorage

    As you are already doing, but you also have to listen to changes in the storage:

    window.addEventListener('storage', () => {
      const stored = window.localStorage.getItem(...)
      // update the store
    })
    

    This works fine if you want the data to persist even if the user browses away.

    BroadcastChannel API

    An alternative approach is to use the BroadcastChannel API where you can create a construction that is only persistent as long as at least 1 tab is open.

    The concept would be the same here: listen to changes in the channel and update the store, if you update the store itself, broacast it.