|
1 | | -import {useState} from 'react' |
| 1 | +import {useState, useEffect} from 'react' |
| 2 | + |
2 | 3 | export const LOAD_MORE_LIMIT_INITIAL = 8 |
3 | 4 | export const LOAD_MORE_LIMIT = 25 |
4 | 5 | export const IMPORT_REGEXP = 'import "regexp"\n' |
@@ -35,9 +36,36 @@ export const useSessionStorage = (keyName: string, defaultValue: any) => { |
35 | 36 | const setValue = (newValue: any) => { |
36 | 37 | try { |
37 | 38 | window.sessionStorage.setItem(keyName, JSON.stringify(newValue)) |
| 39 | + window.dispatchEvent( |
| 40 | + new CustomEvent('same.storage', { |
| 41 | + detail: {key: keyName, oldValue: storedValue, newValue}, |
| 42 | + }) |
| 43 | + ) |
38 | 44 | } catch (err) {} |
39 | 45 | setStoredValue(newValue) |
40 | 46 | } |
41 | 47 |
|
| 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 | + |
42 | 70 | return [storedValue, setValue] |
43 | 71 | } |
0 commit comments