mirror of
https://github.com/vrc-get/vrc-get.git
synced 2026-06-21 09:58:08 +00:00
20 lines
536 B
TypeScript
20 lines
536 B
TypeScript
import { useSyncExternalStore } from "react";
|
|
|
|
const subscribe = (callback: () => void) => {
|
|
window.addEventListener("storage", callback);
|
|
return () => {
|
|
window.removeEventListener("storage", callback);
|
|
};
|
|
};
|
|
|
|
export function useSessionStorage<TData>(options: {
|
|
key: string;
|
|
fallbackValue: TData;
|
|
parse: (s: string) => TData;
|
|
}): TData {
|
|
return useSyncExternalStore(subscribe, () => {
|
|
const value = sessionStorage.getItem(options.key);
|
|
if (value == null) return options.fallbackValue;
|
|
return options.parse(value);
|
|
});
|
|
}
|