-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuseFiler.js
More file actions
44 lines (37 loc) · 861 Bytes
/
useFiler.js
File metadata and controls
44 lines (37 loc) · 861 Bytes
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
import shortid from 'shortid'
import {useLocalStorage} from './main'
const useFiler = key => {
const [files, setFiles] = useLocalStorage(key, {})
const add = (data, id) => {
const newKey = id || shortid.generate()
const now = Date.now()
setFiles(files => ({
...files,
[newKey]: {
id: newKey,
created: now,
modified: now,
data
}
}))
return newKey
}
const remove = id => {
setFiles(({[id]: deleted, ...newFiles}) => newFiles)
}
const update = (id, data) => {
setFiles(files => ({
...files,
[id]: {
...files[id],
modified: Date.now(),
data: typeof data === 'function' ? data(files[id]) : data
}
}))
}
const clear = () => {
setFiles({})
}
return [files, {add, remove, update, clear}]
}
export default useFiler