( key: string, initialValue: T | (() => T), onValueSet?: (any, string) => void, )
| 143 | |
| 144 | // Forked from https://usehooks.com/useLocalStorage/ |
| 145 | export function useLocalStorage<T>( |
| 146 | key: string, |
| 147 | initialValue: T | (() => T), |
| 148 | onValueSet?: (any, string) => void, |
| 149 | ): [T, (value: T | (() => T)) => void] { |
| 150 | const getValueFromLocalStorage = useCallback(() => { |
| 151 | try { |
| 152 | const item = localStorageGetItem(key); |
| 153 | if (item != null) { |
| 154 | return JSON.parse(item); |
| 155 | } |
| 156 | } catch (error) { |
| 157 | console.log(error); |
| 158 | } |
| 159 | if (typeof initialValue === 'function') { |
| 160 | return ((initialValue: any): () => T)(); |
| 161 | } else { |
| 162 | return initialValue; |
| 163 | } |
| 164 | }, [initialValue, key]); |
| 165 | |
| 166 | const storedValue = useSyncExternalStore( |
| 167 | useCallback( |
| 168 | function subscribe(callback) { |
| 169 | window.addEventListener(key, callback); |
| 170 | return function unsubscribe() { |
| 171 | window.removeEventListener(key, callback); |
| 172 | }; |
| 173 | }, |
| 174 | [key], |
| 175 | ), |
| 176 | getValueFromLocalStorage, |
| 177 | ); |
| 178 | |
| 179 | const setValue = useCallback( |
| 180 | (value: $FlowFixMe) => { |
| 181 | try { |
| 182 | const valueToStore = |
| 183 | value instanceof Function ? (value: any)(storedValue) : value; |
| 184 | localStorageSetItem(key, JSON.stringify(valueToStore)); |
| 185 | |
| 186 | // Notify listeners that this setting has changed. |
| 187 | window.dispatchEvent(new Event(key)); |
| 188 | |
| 189 | if (onValueSet != null) { |
| 190 | onValueSet(valueToStore, key); |
| 191 | } |
| 192 | } catch (error) { |
| 193 | console.log(error); |
| 194 | } |
| 195 | }, |
| 196 | [key, storedValue], |
| 197 | ); |
| 198 | |
| 199 | // Listen for changes to this local storage value made from other windows. |
| 200 | // This enables the e.g. "⚛ Elements" tab to update in response to changes from "⚛ Settings". |
| 201 | useLayoutEffect(() => { |
| 202 | // $FlowFixMe[missing-local-annot] |
no test coverage detected