forked from TanStack/tanstack.com
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuseLocalStorage.ts
More file actions
50 lines (45 loc) · 1.24 KB
/
Copy pathuseLocalStorage.ts
File metadata and controls
50 lines (45 loc) · 1.24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
import { useState, useEffect } from "react";
function getWithExpiry<T>(key: string) {
if (typeof window !== "undefined") {
const itemStr = localStorage.getItem(key);
// if the item doesn't exist, return undefined
if (!itemStr) {
return undefined;
}
const item: { value: T; ttl: number } = JSON.parse(itemStr);
// If there is no TTL set, return the value
if (!item.ttl) {
return item.value;
}
// compare the expiry time of the item with the current time
if (new Date().getTime() > item.ttl) {
// If the item is expired, delete the item from storage
localStorage.removeItem(key);
return undefined;
}
return item.value;
}
}
export function useLocalStorage<T>(
key: string,
defaultValue: T,
ttl?: number
): [T, typeof setValue] {
const [value, setValue] = useState(defaultValue);
useEffect(() => {
const item = getWithExpiry<T>(key);
if (item !== undefined) setValue(item);
}, []);
useEffect(() => {
if (value !== defaultValue) {
localStorage.setItem(
key,
JSON.stringify({
value,
ttl: ttl ? new Date().getTime() + ttl : null,
})
);
}
}, [key, value, ttl, defaultValue]);
return [value, setValue];
}