-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.ts
39 lines (34 loc) · 1.07 KB
/
index.ts
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
import { ref, UnwrapRef, reactive, watch, WatchOptions } from 'vue';
const isObject = (o): o is object => {
return typeof o === 'object';
}
const isFunction = (f): f is Function => {
return typeof f === 'function';
}
export const useState = <T>(defaultValue: T) => {
if (isObject(defaultValue)) {
return useStateObj(defaultValue);
}
const state = ref(defaultValue);
const set = (value: T): void => {
state.value = value as UnwrapRef<T>;
};
return [state, set];
};
const useStateObj = <O extends object>(defaultObj: O) => {
const obj = reactive(defaultObj);
const set = (valueObj: O): void => {
Object.entries(valueObj).forEach(([key, val]) => {
obj[key] = val;
});
};
return [obj, set];
}
export const useEffect = (effectHandler, dependencies) => {
return watch(dependencies, (changedDependencies, prevDependencies, onCleanUp) => {
const effectCleaner = effectHandler(changedDependencies, prevDependencies);
if (isFunction(effectCleaner)) {
onCleanUp(effectCleaner);
}
}, { immediate: true, deep: true } as WatchOptions);
}