Skip to content

Commit 97fa280

Browse files
authored
fix: keep session stores in sync (#5550)
1 parent 780bde7 commit 97fa280

File tree

1 file changed

+29
-1
lines changed

1 file changed

+29
-1
lines changed

src/dataExplorer/shared/utils.ts

Lines changed: 29 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
1-
import {useState} from 'react'
1+
import {useState, useEffect} from 'react'
2+
23
export const LOAD_MORE_LIMIT_INITIAL = 8
34
export const LOAD_MORE_LIMIT = 25
45
export const IMPORT_REGEXP = 'import "regexp"\n'
@@ -35,9 +36,36 @@ export const useSessionStorage = (keyName: string, defaultValue: any) => {
3536
const setValue = (newValue: any) => {
3637
try {
3738
window.sessionStorage.setItem(keyName, JSON.stringify(newValue))
39+
window.dispatchEvent(
40+
new CustomEvent('same.storage', {
41+
detail: {key: keyName, oldValue: storedValue, newValue},
42+
})
43+
)
3844
} catch (err) {}
3945
setStoredValue(newValue)
4046
}
4147

48+
// multiple implementations of the same provider, though they share the same state
49+
// in window.sessionStorage, will fall out of sync as their setStoredValue
50+
// functions dont know about each other. there's a 'storage' event on window built
51+
// to mitigate that issue, but it's only fired across tabs, which session storage
52+
// doesn't even operate across. So here we're generating a custom event to keep
53+
// all inter-tab invokations of the session storage hook in sync.
54+
useEffect(() => {
55+
const listen = (evt: CustomEvent) => {
56+
if (!evt.detail.key || evt.detail.key !== keyName) {
57+
return
58+
}
59+
60+
setStoredValue(evt.detail.newValue)
61+
}
62+
63+
window.addEventListener('same.storage', listen)
64+
65+
return () => {
66+
window.removeEventListener('same.storage', listen)
67+
}
68+
}, [])
69+
4270
return [storedValue, setValue]
4371
}

0 commit comments

Comments
 (0)