forked from sheepzh/time-tracker-4-browser
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuseCached.ts
More file actions
56 lines (51 loc) · 1.64 KB
/
useCached.ts
File metadata and controls
56 lines (51 loc) · 1.64 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
51
52
53
54
55
56
/**
* Copyright (c) 2022-present Hengyang Zhang
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
import { onBeforeMount, ref, type Ref, watch } from "vue"
import { useState } from "."
const getInitialValue = <T>(key: string, defaultValue?: T): T | undefined => {
if (!key) return defaultValue
const exist = localStorage.getItem(key)
if (!exist) return defaultValue
try {
return JSON.parse(exist) as T
} catch (e) {
return undefined
}
}
const saveCache = <T>(key: string, val: T) => {
if (!key) return
if (val === null || val === undefined || val === '') {
localStorage.removeItem(key)
} else {
localStorage.setItem(key, JSON.stringify(val))
}
}
export function useCached<T>(key: string, defaultValue: T, defaultFirst?: boolean): { data: Ref<T>, setter: (val: T) => void }
export function useCached<T>(
key: string | undefined,
defaultValue?: T,
defaultFirst?: boolean,
): { data: Ref<T | undefined>, setter: (val: T | undefined) => void }
export function useCached<T>(
key: string | undefined,
defaultValue?: T,
defaultFirst?: boolean,
) {
if (!key) {
const [data, setter] = useState(defaultValue)
return { data, setter }
}
const data: Ref<T | undefined> = ref<T>()
const setter = (val: T | undefined) => data.value = val
onBeforeMount(() => {
let cachedValue = getInitialValue(key, defaultValue)
let initial = defaultFirst ? defaultValue || cachedValue : cachedValue
setter(initial)
})
watch(data, () => saveCache(key, data.value))
return { data, setter }
}