/
useful.hooks.js
77 lines (66 loc) · 1.76 KB
/
useful.hooks.js
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
/* A collection of useful custom hooks */
const useAsync = (scope, func, init)=>{
const [pending, setPending] = scope.useState(false);
const [error, setError] = scope.useState(null);
const [result, setResult] = scope.useState(init);
let wrapper = scope.useRef((...args)=>{
setPending(true);
setError(null);
return func(...args)
.then((content)=>setResult(content))
.catch((err)=>setError(err))
.finally(()=>setPending(false));
});
wrapper.pending= pending;
wrapper.error = error;
wrapper.result = result;
return wrapper;
};
//Built-in
xo.Hooks.useAsync = function(asyncFn, init){
if(!this.hook.fn){
this.hook.fn = (...args)=>{
this.hook.fn.pending = true;
this.hook.fn.error = null;
this.instance.redraw();
return asyncFn(...args)
.then(res=>{ this.hook.fn.result=res; return res; })
.catch(err=>{ this.hook.fn.error=err; return err; })
.finally(res=>{
this.hook.fn.pending=false;
this.instance.redraw();
return res;
});
};
this.hook.fn.result=init;
}
return this.hook.fn;
};
const useLocalStorage = (scope, key, init)=>{
const [val, setVal] = scope.useState(init);
scope.useEffect(()=>{
try{
const storedVal = localStorage.getItem(key);
if(storedVal) setVal(JSON.parse(storedVal));
}catch(err){}
});
return [val, (newVal)=>{
localStorage.setItem(key, JSON.stringify(newVal));
setVal(newVal);
}];
};
xo.Hooks.useLocalStorage = function(key, init){
};
const useSessionStorage = (scope, key, init)=>{
const [val, setVal] = scope.useState(init);
scope.useEffect(()=>{
try{
const storedVal = sessionStorage.getItem(key);
if(storedVal) setVal(JSON.parse(storedVal));
}catch(err){}
});
return [val, (newVal)=>{
sessionStorage.setItem(key, JSON.stringify(newVal));
setVal(newVal);
}];
};