Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Read storage on window.onstorage #7137

Merged
merged 1 commit into from
Dec 17, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions src/state/persisted/index.web.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ const _emitter = new EventEmitter()

export async function init() {
broadcast.onmessage = onBroadcastMessage
window.onstorage = onStorage
const stored = readFromStorage()
if (stored) {
_state = stored
Expand Down Expand Up @@ -90,6 +91,17 @@ export async function clearStorage() {
}
clearStorage satisfies PersistedApi['clearStorage']

function onStorage() {
const next = readFromStorage()
if (next === _state) {
return
}
if (next) {
_state = next
_emitter.emit('update')
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we need this emit? Looks like we might be able to remove the update event now, since we always emit the more modern event with the key that changed.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we do. If the BroadcastChannel thing arrives too early, it will get ignored. And then by the time we get the storage event, we don't know what changed exactly, so we have to deopt. We could try to be smarter about this but I'd prefer to keep it simple and then revisit the assumptions.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In other words we don't know the key if we use the storage event. So this part needs rethinking

}
}

async function onBroadcastMessage({data}: MessageEvent) {
if (
typeof data === 'object' &&
Expand Down
Loading