|
| 1 | +export interface StorageManager { |
| 2 | + (options: { key: string; storageWindow?: Window | null }): { |
| 3 | + /** |
| 4 | + * Function to get the value from the storage |
| 5 | + * @param defaultValue The default value to be returned if the key is not found |
| 6 | + * @returns The value from the storage or the default value |
| 7 | + */ |
| 8 | + get(defaultValue: any): any; |
| 9 | + /** |
| 10 | + * Function to set the value in the storage |
| 11 | + * @param value The value to be set |
| 12 | + * @returns void |
| 13 | + */ |
| 14 | + set(value: any): void; |
| 15 | + /** |
| 16 | + * Function to subscribe to the value of the specified key triggered by external events |
| 17 | + * @param handler The function to be called when the value changes |
| 18 | + * @returns A function to unsubscribe the handler |
| 19 | + * @example |
| 20 | + * React.useEffect(() => { |
| 21 | + * const unsubscribe = storageManager.subscribe((value) => { |
| 22 | + * console.log(value); |
| 23 | + * }); |
| 24 | + * return unsubscribe; |
| 25 | + * }, []); |
| 26 | + */ |
| 27 | + subscribe(handler: (value: any) => void): () => void; |
| 28 | + }; |
| 29 | +} |
| 30 | + |
| 31 | +function noop() {} |
| 32 | + |
| 33 | +const localStorageManager: StorageManager = ({ key, storageWindow }) => { |
| 34 | + if (!storageWindow && typeof window !== 'undefined') { |
| 35 | + storageWindow = window; |
| 36 | + } |
| 37 | + return { |
| 38 | + get(defaultValue) { |
| 39 | + if (typeof window === 'undefined') { |
| 40 | + return undefined; |
| 41 | + } |
| 42 | + if (!storageWindow) { |
| 43 | + return defaultValue; |
| 44 | + } |
| 45 | + let value; |
| 46 | + try { |
| 47 | + value = storageWindow.localStorage.getItem(key); |
| 48 | + } catch { |
| 49 | + // Unsupported |
| 50 | + } |
| 51 | + return value || defaultValue; |
| 52 | + }, |
| 53 | + set: (value) => { |
| 54 | + if (storageWindow) { |
| 55 | + try { |
| 56 | + storageWindow.localStorage.setItem(key, value); |
| 57 | + } catch { |
| 58 | + // Unsupported |
| 59 | + } |
| 60 | + } |
| 61 | + }, |
| 62 | + subscribe: (handler) => { |
| 63 | + if (!storageWindow) { |
| 64 | + return noop; |
| 65 | + } |
| 66 | + const listener = (event: StorageEvent) => { |
| 67 | + const value = event.newValue; |
| 68 | + if (event.key === key) { |
| 69 | + handler(value); |
| 70 | + } |
| 71 | + }; |
| 72 | + storageWindow.addEventListener('storage', listener); |
| 73 | + return () => { |
| 74 | + storageWindow.removeEventListener('storage', listener); |
| 75 | + }; |
| 76 | + }, |
| 77 | + }; |
| 78 | +}; |
| 79 | + |
| 80 | +export default localStorageManager; |
0 commit comments