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
41 lines (36 loc) · 1.06 KB
/
useCached.ts
File metadata and controls
41 lines (36 loc) · 1.06 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
/**
* Copyright (c) 2022-present Hengyang Zhang
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
import { onMounted, ref, Ref, watch } from "vue"
type Result<T> = {
data: Ref<T>
setter: (val: T) => void
}
const getInitialValue = <T>(key: string, defaultValue?: T): T => {
if (!key) return defaultValue
const exist = localStorage.getItem(key)
if (!exist) return defaultValue
try {
return JSON.parse(exist) as T
} catch (e) {
return null
}
}
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 const useCached = <T>(key: string, defaultValue?: T): Result<T> => {
const data: Ref<T> = ref<T>()
const setter = (val: T) => data.value = val
onMounted(() => setter(getInitialValue(key, defaultValue)))
watch(data, () => saveCache(key, data.value))
return { data, setter }
}