Skip to content

Commit 1096459

Browse files
committed
Merge branch 'main' into experimental
2 parents 7dc2077 + 4988f92 commit 1096459

File tree

1 file changed

+66
-0
lines changed

1 file changed

+66
-0
lines changed

index.js

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,10 @@ function throttle(cb, ms) {
4040
};
4141
}
4242

43+
const dispatchStorageEvent = (key, newValue) => {
44+
window.dispatchEvent(new StorageEvent("storage", { key, newValue }));
45+
};
46+
4347
export function useBattery() {
4448
const [state, setState] = React.useState({
4549
supported: true,
@@ -1431,6 +1435,68 @@ export function useScript(src, options = {}) {
14311435
return status;
14321436
}
14331437

1438+
const setSessionStorageItem = (key, value) => {
1439+
const stringifiedValue = JSON.stringify(value);
1440+
window.sessionStorage.setItem(key, stringifiedValue);
1441+
dispatchStorageEvent(key, stringifiedValue);
1442+
};
1443+
1444+
const removeSessionStorageItem = (key) => {
1445+
window.sessionStorage.removeItem(key);
1446+
dispatchStorageEvent(key, null);
1447+
};
1448+
1449+
const getSessionStorageItem = (key) => {
1450+
return window.sessionStorage.getItem(key);
1451+
};
1452+
1453+
const useSessionStorageSubscribe = (callback) => {
1454+
window.addEventListener("storage", callback);
1455+
return () => window.removeEventListener("storage", callback);
1456+
};
1457+
1458+
const getSessionStorageServerSnapshot = () => {
1459+
throw Error("useSessionStorage is a client-only hook");
1460+
};
1461+
1462+
export function useSessionStorage(key, initialValue) {
1463+
const getSnapshot = () => getSessionStorageItem(key);
1464+
1465+
const store = React.useSyncExternalStore(
1466+
useSessionStorageSubscribe,
1467+
getSnapshot,
1468+
getSessionStorageServerSnapshot
1469+
);
1470+
1471+
const setState = React.useCallback(
1472+
(v) => {
1473+
try {
1474+
const nextState = typeof v === "function" ? v(JSON.parse(store)) : v;
1475+
1476+
if (nextState === undefined || nextState === null) {
1477+
removeSessionStorageItem(key);
1478+
} else {
1479+
setSessionStorageItem(key, nextState);
1480+
}
1481+
} catch (e) {
1482+
console.warn(e);
1483+
}
1484+
},
1485+
[key, store]
1486+
);
1487+
1488+
React.useEffect(() => {
1489+
if (
1490+
getSessionStorageItem(key) === null &&
1491+
typeof initialValue !== "undefined"
1492+
) {
1493+
setSessionStorageItem(key, initialValue);
1494+
}
1495+
}, [key, initialValue]);
1496+
1497+
return [store ? JSON.parse(store) : initialValue, setState];
1498+
}
1499+
14341500
export function useSet(values) {
14351501
const setRef = React.useRef(new Set(values));
14361502
const [, reRender] = React.useReducer((x) => x + 1, 0);

0 commit comments

Comments
 (0)