|
| 1 | +// Copyright 2023 The Perses Authors |
| 2 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 3 | +// you may not use this file except in compliance with the License. |
| 4 | +// You may obtain a copy of the License at |
| 5 | +// |
| 6 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 7 | +// |
| 8 | +// Unless required by applicable law or agreed to in writing, software |
| 9 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 10 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 11 | +// See the License for the specific language governing permissions and |
| 12 | +// limitations under the License. |
| 13 | + |
| 14 | +import { useState, useCallback } from 'react'; |
| 15 | + |
| 16 | +type StorageTuple<T> = [T, (next: T) => void]; |
| 17 | + |
| 18 | +/** |
| 19 | + * Just like useState but gets/sets the value in the browser's local storage. |
| 20 | + * 'key' should be a constant string. 'initialValue' is returned when local |
| 21 | + * storage does not have any data yet. |
| 22 | + */ |
| 23 | +export function useLocalStorage<T>(key: string, initialValue: T): StorageTuple<T> { |
| 24 | + const { value, setValueAndStore } = useStorage(window.localStorage, key, initialValue); |
| 25 | + return [value, setValueAndStore]; |
| 26 | +} |
| 27 | + |
| 28 | +// Common functionality used by all storage hooks |
| 29 | +function useStorage<T>( |
| 30 | + storage: Storage, |
| 31 | + key: string, |
| 32 | + initialValue: T |
| 33 | +): { |
| 34 | + setValueAndStore: (value: T) => void; |
| 35 | + setValue: (value: T) => void; |
| 36 | + value: T; |
| 37 | +} { |
| 38 | + // Use state so that changes cause the page to re-render |
| 39 | + const [value, setValue] = useState<T>(() => { |
| 40 | + try { |
| 41 | + const json = storage.getItem(key); |
| 42 | + if (json !== null) { |
| 43 | + return JSON.parse(json); |
| 44 | + } |
| 45 | + } catch { |
| 46 | + // No-op |
| 47 | + } |
| 48 | + |
| 49 | + // Either the value isn't in storage yet or JSON parsing failed, so |
| 50 | + // set to the initial value in both places |
| 51 | + storage.setItem(key, JSON.stringify(initialValue)); |
| 52 | + return initialValue; |
| 53 | + }); |
| 54 | + |
| 55 | + // Set in both places |
| 56 | + const setValueAndStore = useCallback( |
| 57 | + (val: T) => { |
| 58 | + setValue(val); |
| 59 | + storage.setItem(key, JSON.stringify(val)); |
| 60 | + }, |
| 61 | + [setValue, storage, key] |
| 62 | + ); |
| 63 | + |
| 64 | + return { value, setValue, setValueAndStore }; |
| 65 | +} |
0 commit comments