1

I'm creating a Store in Svelte that subscribes to value changes and stores the value on localStorage.

When opening the page there is an input tag with the value binded to the store. Everything works as intended and after refreshing the last value is there.

My problem and what I don't know how to achieve (If it's even possible) Having a 2nd tab of the same page open, as I type in one I want to see the value update on the other tab.

(I understand that the problem is that this 2nd tab is not aware of localStorage changing)

My hack solution was an interval reading an updating the value from localStorage, but that's clearly a hack and not a solution.

How would we go around something like this?

Here is a gist with the 2 files used. https://gist.github.com/MrAmericanMike/b2ddea28e4a4716e43abe03c6211c8b7

MrAmericanMike
  • 129
  • 2
  • 10

1 Answers1

5

There are two solutions to this, depending a bit on the use case.

use an event listener

You can register an event listener on the window that listens to the storage event and checks if the item you are interested in is the one that has changed.:

window.addEventListener('storage', event => {
  if (event.key == 'DATA') {
    // do something with the newly updated store
  }
})

https://developer.mozilla.org/en-US/docs/Web/API/Window/storage_event full example here: https://stackoverflow.com/a/68785061/11956107

use a BroadcastChannel

This is a touch trickier and fits the use case where you do no want the data to be actually persistant (that is: it is reset to the default if the user closes all tabs).

https://developer.mozilla.org/en-US/docs/Web/API/Broadcast_Channel_API

Stephane Vanraes
  • 14,343
  • 2
  • 23
  • 41