Skip to content

Commit cba668a

Browse files
committed
fix(persist-localstorage): add ssr-safety
1 parent 50ac608 commit cba668a

File tree

1 file changed

+15
-11
lines changed
  • src/persist-localstorage-experimental

1 file changed

+15
-11
lines changed

src/persist-localstorage-experimental/index.ts

Lines changed: 15 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -31,17 +31,21 @@ export function persistWithLocalStorage(
3131
buster = '',
3232
}: Options = {}
3333
) {
34-
const saveCache = throttle(() => {
35-
const storageCache: LocalStorageCache = {
36-
buster,
37-
timestamp: Date.now(),
38-
cacheState: dehydrate(queryClient),
39-
}
34+
if (typeof window !== 'undefined') {
35+
// Subscribe to changes
36+
const saveCache = throttle(() => {
37+
const storageCache: LocalStorageCache = {
38+
buster,
39+
timestamp: Date.now(),
40+
cacheState: dehydrate(queryClient),
41+
}
42+
43+
localStorage.setItem(localStorageKey, JSON.stringify(storageCache))
44+
}, throttleTime)
4045

41-
localStorage.setItem(localStorageKey, JSON.stringify(storageCache))
42-
}, throttleTime)
46+
queryClient.getQueryCache().subscribe(saveCache)
4347

44-
if (typeof localStorage !== 'undefined') {
48+
// Attempt restore
4549
const cacheStorage = localStorage.getItem(localStorageKey)
4650

4751
if (!cacheStorage) {
@@ -58,9 +62,9 @@ export function persistWithLocalStorage(
5862
} else {
5963
hydrate(queryClient, cache.cacheState)
6064
}
65+
} else {
66+
localStorage.removeItem(localStorageKey)
6167
}
62-
63-
queryClient.getQueryCache().subscribe(saveCache)
6468
}
6569
}
6670

0 commit comments

Comments
 (0)