rsnext/examples/with-mobx-react-lite/store.js
Ivan V 14cb6556a8
example fix: hydrate method of the mobx store needs to be an action (#19522)
By default, MobX 6 and later require that you use `actions` to make changes to the state, otherwise, it issues a warning in the console, because the `hydrate` method of the `store.js` class hasn't been declared an action, you can see this warning if you try to load pages that use hydration (ssg, ssr).
This pull request fixes that.

More info about the behavior:
https://mobx.js.org/actions.html#disabling-mandatory-actions-
2020-11-25 17:20:57 +00:00

46 lines
1 KiB
JavaScript

import { action, observable, computed, runInAction, makeObservable } from 'mobx'
import { enableStaticRendering } from 'mobx-react-lite'
enableStaticRendering(typeof window === 'undefined')
export class Store {
lastUpdate = 0
light = false
constructor() {
makeObservable(this, {
lastUpdate: observable,
light: observable,
start: action,
hydrate: action,
timeString: computed,
})
}
start = () => {
this.timer = setInterval(() => {
runInAction(() => {
this.lastUpdate = Date.now()
this.light = true
})
}, 1000)
}
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
}
}