Files
teleport/web/packages/shared/hooks/useLocalStorage.ts
T
18652a7ea4 Bump typescript-eslint from 7.14.1 to 8.12.2 (#48275)
* Bump typescript-eslint from 7.14.1 to 8.12.2

Bumps [typescript-eslint](https://github.com/typescript-eslint/typescript-eslint/tree/HEAD/packages/typescript-eslint) from 7.14.1 to 8.12.2.
- [Release notes](https://github.com/typescript-eslint/typescript-eslint/releases)
- [Changelog](https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/typescript-eslint/CHANGELOG.md)
- [Commits](https://github.com/typescript-eslint/typescript-eslint/commits/v8.12.2/packages/typescript-eslint)

---
updated-dependencies:
- dependency-name: typescript-eslint
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>

* Allow conditionals for no-unused-expressions, fix remaining issues

* Fix no-unused-vars violations in try catch blocks

* no-empty-object-type: Allow empty interfaces with single extends

* Allow no-require-imports in JS files

* Mark force reflow with void

---------

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Rafał Cieślak <rafal.cieslak@goteleport.com>
Co-authored-by: Michael Myers <michael.myers@goteleport.com>
2024-11-19 16:00:11 +00:00

61 lines
1.6 KiB
TypeScript

/**
* Teleport
* Copyright (C) 2023 Gravitational, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import {
Dispatch,
SetStateAction,
useCallback,
useEffect,
useState,
} from 'react';
export function useLocalStorage<T>(
key: string,
initialValue: T
): [T, Dispatch<SetStateAction<T>>] {
const read = useCallback(() => {
const value = window.localStorage.getItem(key);
if (!value) {
return initialValue;
}
try {
return JSON.parse(value) as T;
} catch {
return initialValue;
}
}, [initialValue, key]);
const [storedValue, setStoredValue] = useState<T>(read());
const write = useCallback((value: SetStateAction<T>) => {
const newValue = value instanceof Function ? value(storedValue) : value;
window.localStorage.setItem(key, JSON.stringify(newValue));
setStoredValue(newValue);
}, []);
useEffect(() => {
setStoredValue(read());
}, []);
return [storedValue, write];
}