1
0
Fork 0
mirror of https://github.com/terribleplan/next.js.git synced 2024-01-19 02:48:18 +00:00
next.js/examples/with-mobx/store.js
Már Örlygsson 420f74c867 examples/with-mobx : Fix and simplify (#5537)
I spent far too much time fiddling with this example project before realizing it contained a bug in the store initialization logic and it was a bit more complex than it needed to be.

* The custom server was not needed
* The store-initialization did effectively the same thing twice for no reason
* And wrapping MyApp component in a HOC was wholly unnecessary indirection

My changes are split into four discrete commits for clarity.
2018-11-06 10:18:26 +01:00

38 lines
907 B
JavaScript

import { action, observable } from 'mobx'
import { useStaticRendering } from 'mobx-react'
const isServer = typeof window === 'undefined'
useStaticRendering(isServer)
class Store {
@observable lastUpdate = 0
@observable light = false
constructor (isServer, initialData = {}) {
this.lastUpdate = initialData.lastUpdate != null ? initialData.lastUpdate : Date.now()
this.light = !!initialData.light
}
@action start = () => {
this.timer = setInterval(() => {
this.lastUpdate = Date.now()
this.light = true
}, 1000)
}
stop = () => clearInterval(this.timer)
}
let store = null
export function initializeStore (initialData) {
// Always make a new store if server, otherwise state is shared between requests
if (isServer) {
return new Store(isServer, initialData)
}
if (store === null) {
store = new Store(isServer, initialData)
}
return store
}