2020-06-06 18:57:16 +02:00
|
|
|
import { useMemo } from 'react'
|
2018-04-03 09:09:30 +02:00
|
|
|
import { init } from '@rematch/core'
|
|
|
|
import { counter, github } from './models'
|
|
|
|
|
2020-06-06 18:57:16 +02:00
|
|
|
let store
|
|
|
|
|
2019-05-12 11:13:02 +02:00
|
|
|
const exampleInitialState = {
|
2019-11-11 04:24:53 +01:00
|
|
|
counter: 5,
|
2018-04-03 09:09:30 +02:00
|
|
|
}
|
2019-03-18 14:37:49 +01:00
|
|
|
|
2020-06-06 18:57:16 +02:00
|
|
|
export const initStore = (initialState = exampleInitialState) =>
|
2019-05-29 01:06:13 +02:00
|
|
|
init({
|
|
|
|
models: {
|
|
|
|
counter,
|
2019-11-11 04:24:53 +01:00
|
|
|
github,
|
2019-05-29 01:06:13 +02:00
|
|
|
},
|
|
|
|
redux: {
|
2019-11-11 04:24:53 +01:00
|
|
|
initialState,
|
|
|
|
},
|
2019-05-29 01:06:13 +02:00
|
|
|
})
|
2020-06-06 18:57:16 +02:00
|
|
|
|
|
|
|
export const initializeStore = (preloadedState) => {
|
|
|
|
let _store = store ?? initStore(preloadedState)
|
|
|
|
|
|
|
|
// After navigating to a page with an initial Redux state, merge that state
|
|
|
|
// with the current state in the store, and create a new store
|
|
|
|
if (preloadedState && store) {
|
|
|
|
_store = initStore({
|
|
|
|
...store.getState(),
|
|
|
|
...preloadedState,
|
|
|
|
})
|
|
|
|
// Reset the current store
|
|
|
|
store = undefined
|
|
|
|
}
|
|
|
|
|
|
|
|
// 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
|
|
|
|
}
|