2020-05-31 18:53:01 +02:00
|
|
|
import { useMemo } from 'react'
|
2019-03-14 17:40:00 +01:00
|
|
|
import { createStore, applyMiddleware } from 'redux'
|
|
|
|
import { composeWithDevTools } from 'redux-devtools-extension'
|
|
|
|
import thunkMiddleware from 'redux-thunk'
|
2020-04-15 01:36:50 +02:00
|
|
|
import reducers from './reducers'
|
2019-03-14 17:40:00 +01:00
|
|
|
|
2020-05-31 18:53:01 +02:00
|
|
|
let store
|
|
|
|
|
|
|
|
function initStore(initialState) {
|
|
|
|
return createStore(
|
2020-04-15 01:36:50 +02:00
|
|
|
reducers,
|
|
|
|
initialState,
|
|
|
|
composeWithDevTools(applyMiddleware(thunkMiddleware))
|
|
|
|
)
|
2020-05-31 18:53:01 +02:00
|
|
|
}
|
2019-03-14 17:40:00 +01:00
|
|
|
|
2020-05-31 18:53:01 +02:00
|
|
|
export const initializeStore = (preloadedState) => {
|
|
|
|
let _store = store ?? initStore(preloadedState)
|
2019-03-14 17:40:00 +01:00
|
|
|
|
2020-05-31 18:53:01 +02:00
|
|
|
// 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,
|
2020-04-15 01:36:50 +02:00
|
|
|
})
|
2020-05-31 18:53:01 +02:00
|
|
|
// Reset the current store
|
|
|
|
store = undefined
|
2019-03-14 17:40:00 +01:00
|
|
|
}
|
|
|
|
|
2020-05-31 18:53:01 +02:00
|
|
|
// 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])
|
2020-04-15 01:36:50 +02:00
|
|
|
return store
|
2019-03-14 17:40:00 +01:00
|
|
|
}
|