2022-02-08 12:06:25 +01:00
|
|
|
// Get an item from localStorage.
|
|
|
|
// Returns undefined if the browser denies access.
|
|
|
|
export function getLocalStorageItem<T>(key: string): T | undefined {
|
|
|
|
try {
|
|
|
|
return parseStoredItem<T>(window.localStorage.getItem(key));
|
|
|
|
} catch (err: unknown) {
|
|
|
|
console.warn(err);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Store an item in localStorage.
|
|
|
|
// Does nothing if the browser denies access.
|
|
|
|
export function setLocalStorageItem(key: string, value: unknown) {
|
|
|
|
try {
|
2023-01-03 14:41:34 +01:00
|
|
|
window.localStorage.setItem(
|
|
|
|
key,
|
|
|
|
JSON.stringify(value, (_key, value) =>
|
2023-10-02 14:25:46 +02:00
|
|
|
value instanceof Set ? [...value] : value,
|
|
|
|
),
|
2023-01-03 14:41:34 +01:00
|
|
|
);
|
2022-02-08 12:06:25 +01:00
|
|
|
} catch (err: unknown) {
|
|
|
|
console.warn(err);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Parse an item from localStorage.
|
|
|
|
// Returns undefined if the item could not be parsed.
|
|
|
|
function parseStoredItem<T>(data: string | null): T | undefined {
|
|
|
|
try {
|
|
|
|
return data ? JSON.parse(data) : undefined;
|
|
|
|
} catch (err: unknown) {
|
|
|
|
console.warn(err);
|
|
|
|
}
|
|
|
|
}
|