-
Notifications
You must be signed in to change notification settings - Fork 2
/
store.js
60 lines (49 loc) · 1.56 KB
/
store.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
import { action, observable, computed, runInAction } from 'mobx'
import { useStaticRendering } from 'mobx-react'
import { useMemo } from 'react'
// eslint-disable-next-line react-hooks/rules-of-hooks
useStaticRendering(typeof window === 'undefined')
let store
class Store {
@observable lastUpdate = 0
@observable light = false
@action start = () => {
this.timer = setInterval(() => {
runInAction(() => {
this.lastUpdate = Date.now()
this.light = true
})
}, 1000)
}
@computed get timeString() {
const pad = (n) => (n < 10 ? `0${n}` : n)
const format = (t) =>
`${pad(t.getUTCHours())}:${pad(t.getUTCMinutes())}:${pad(
t.getUTCSeconds()
)}`
return format(new Date(this.lastUpdate))
}
stop = () => clearInterval(this.timer)
hydrate = (data) => {
if (!data) return
this.lastUpdate = data.lastUpdate !== null ? data.lastUpdate : Date.now()
this.light = !!data.light
}
}
function initializeStore(initialData = null) {
const _store = store ?? new Store()
// If your page has Next.js data fetching methods that use a Mobx store, it will
// get hydrated here, check `pages/ssg.js` and `pages/ssr.js` for more details
if (initialData) {
_store.hydrate(initialData)
}
// For SSG and SSR always create a new store
if (typeof window === 'undefined') return _store
// Create the store once in the client
if (!store) store = _store
return _store
}
export function useStore(initialState) {
const store = useMemo(() => initializeStore(initialState), [initialState])
return store
}