rsnext/examples/with-mobx-react-lite/store.js
Joe Haddad 18a9c7e371
Improve linting rules to catch more errors (#9374)
* Update `packages/`

* Update examples

* Update tests

* Update bench

* Update top level files

* Fix build

* trigger
2019-11-10 19:24:53 -08:00

44 lines
1.1 KiB
JavaScript

import { action } from 'mobx'
import { useObservable, useStaticRendering } from 'mobx-react-lite'
import { createContext, useCallback } from 'react'
const isServer = typeof window === 'undefined'
// eslint-disable-next-line react-hooks/rules-of-hooks
useStaticRendering(isServer)
let StoreContext = createContext()
let start
let stop
let store
function initializeData(initialData = store || {}) {
const { lastUpdate = Date.now(), light } = initialData
return {
lastUpdate,
light: Boolean(light),
}
}
function InjectStoreContext({ children, initialData }) {
let timerInterval = null
store = useObservable(initializeData(initialData))
start = useCallback(
action(() => {
timerInterval = setInterval(() => {
store.lastUpdate = Date.now()
store.light = true
}, 1000)
})
)
stop = () => {
if (timerInterval) {
clearInterval(timerInterval)
}
}
return <StoreContext.Provider value={store}>{children}</StoreContext.Provider>
}
export { InjectStoreContext, StoreContext, initializeData, start, stop, store }