( key: string, defaultValueOrInitializeFn: S | ((rawStorageValue?: unknown) => S) )
| 63 | // Initialize state with default value or value from localStorage. |
| 64 | // If window is not defined uses the default value and **does not** throw an error |
| 65 | function initializeStorage<S>( |
| 66 | key: string, |
| 67 | defaultValueOrInitializeFn: S | ((rawStorageValue?: unknown) => S) |
| 68 | ): S { |
| 69 | if (typeof key !== 'string') { |
| 70 | throw new TypeError('useLocalStorage: key must be a string'); |
| 71 | } |
| 72 | |
| 73 | // Return default if env does not support localStorage. Passing null to initializer |
| 74 | // to mimick not having any previously stored value there. |
| 75 | if (!SUPPORTS_LOCAL_STORAGE) { |
| 76 | return defaultOrInitializer(defaultValueOrInitializeFn, undefined, null); |
| 77 | } |
| 78 | |
| 79 | // getItem and try and decode it, if null is returned use default initializer |
| 80 | const jsonEncodedValue = localStorageWrapper.getItem(key); |
| 81 | if (jsonEncodedValue === null) { |
| 82 | return defaultOrInitializer(defaultValueOrInitializeFn, undefined, null); |
| 83 | } |
| 84 | |
| 85 | // We may have failed to parse the value, so just pass it down raw to the initializer |
| 86 | const decodedValue = tryParseStorage(jsonEncodedValue) as S | null; |
| 87 | if (decodedValue === null) { |
| 88 | return defaultOrInitializer(defaultValueOrInitializeFn, undefined, jsonEncodedValue); |
| 89 | } |
| 90 | |
| 91 | // We managed to decode the value, so use it |
| 92 | return defaultOrInitializer(defaultValueOrInitializeFn, decodedValue, jsonEncodedValue); |
| 93 | } |
| 94 | |
| 95 | // Mimicks the behavior of React.useState but keeps state synced with localStorage. |
| 96 | // The only difference from React is that when a state initializer fn is passed, |
no test coverage detected