sindresorhus/electron-store

The `onDidChange` event is not propagating to all windows

zeke opened this issue · 7 comments

zeke commented

I've got two windows open. One of them changes the state object.

store.set('preferences', newPrefs)

document.addEventListener('DOMContentLoaded', () => {
  store.onDidChange('preferences', (newValue, oldValue) => {
    console.log('hello from setting window', newValue, oldValue)
    // works!
  })
})

Another open window is also subscribed to the event, but it doesn't fire:

document.addEventListener('DOMContentLoaded', () => {
  store.onDidChange('preferences', (newValue, oldValue) => {
    console.log('hello from receiving window', newValue, oldValue)
    // does not work :[
  })
})
zeke commented

As a workaround, I could only manipulate store from the app's main process, and use IPC to collect and distribute updates to and from all the windows, but that seems like more plumbing... 🤔

Yes, the events only work in the same process as they were triggered. To make this work we would have to propagate events between the windows and the main process. It's definitely doable, but not trivial.

Can this be done like you did https://github.com/sindresorhus/electron-better-ipc

So onDidChange will be in both main & renderer❓But it seems like electron-store uses conf so you would need another module named electron-conf where onDidChange can be put in both main & renderer right❓I'm just guessing :)

Couldn't this be achieved with fs.watch on the file that can trigger events wherever store is used?

If not, it would be helpful to have a helper function for this so you can send a message via IPC to trigger a check for settings updates. That way it's a lot less boilerplate to set up notifying for each property and propagating the changes through. You would just send a settings-updated message back to the main process or vice versa and then call store.checkForUpdates() when you receive that message to trigger any event handlers.

We now have a watch option.

zeke commented

Nice! That works for my use case. Feel free to close this.