Skip to content

Commit 7a53e92

Browse files
committed
main 🧊 ssr fix storage
1 parent da54bdc commit 7a53e92

File tree

2 files changed

+16
-15
lines changed

2 files changed

+16
-15
lines changed

‎eslint.config.js

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,7 @@ export default eslint(
55
typescript: true,
66
react: true,
77
jsx: true,
8-
vue: true,
9-
stylistic: true
8+
vue: true
109
},
1110
{
1211
name: 'siberiacancode/hooks',

‎src/hooks/useStorage/useStorage.ts

Lines changed: 15 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -81,7 +81,21 @@ export const useStorage = <Value>(
8181
const options = (typeof params === 'object' ? params : undefined) as UseStorageOptions<Value>;
8282
const initialValue = (options ? options?.initialValue : params) as UseStorageInitialValue<Value>;
8383

84-
const storage = options?.storage ?? window.localStorage;
84+
const set = (value: Value) => {
85+
if (value === null) return removeStorageItem(storage, key);
86+
setStorageItem(storage, key, serializer(value));
87+
};
88+
const remove = () => removeStorageItem(storage, key);
89+
90+
91+
if (!isClient)
92+
return {
93+
value: initialValue instanceof Function ? initialValue() : initialValue,
94+
set,
95+
remove
96+
};
97+
98+
const storage = options?.storage ?? window?.localStorage;
8599
const serializer = (value: Value) => {
86100
if (options?.serializer) return options.serializer(value);
87101
return JSON.stringify(value);
@@ -104,11 +118,6 @@ export const useStorage = <Value>(
104118
const getSnapshot = () => getStorageItem(storage, key);
105119
const store = useSyncExternalStore(storageSubscribe, getSnapshot, getServerSnapshot);
106120

107-
const set = (value: Value) => {
108-
if (value === null) return removeStorageItem(storage, key);
109-
setStorageItem(storage, key, serializer(value));
110-
};
111-
112121
useIsomorphicLayoutEffect(() => {
113122
const value = getStorageItem(storage, key);
114123
if (value === undefined && initialValue !== undefined) {
@@ -120,14 +129,7 @@ export const useStorage = <Value>(
120129
}
121130
}, [key]);
122131

123-
const remove = () => removeStorageItem(storage, key);
124132

125-
if (!isClient)
126-
return {
127-
value: initialValue instanceof Function ? initialValue() : initialValue,
128-
set,
129-
remove
130-
};
131133
return {
132134
value: store ? deserializer(store) : undefined,
133135
set,

0 commit comments

Comments
 (0)