2020-05-28 07:12:27 +02:00
|
|
|
import { useMemo } from 'react'
|
2016-12-22 06:10:54 +01:00
|
|
|
import { createStore, applyMiddleware } from 'redux'
|
2017-05-25 18:37:10 +02:00
|
|
|
import { composeWithDevTools } from 'redux-devtools-extension'
|
2016-12-22 06:10:54 +01:00
|
|
|
|
2020-05-28 07:12:27 +02:00
|
|
|
let store
|
|
|
|
|
2019-10-01 19:11:20 +02:00
|
|
|
const initialState = {
|
2017-04-30 22:44:24 +02:00
|
|
|
lastUpdate: 0,
|
|
|
|
light: false,
|
2019-11-11 04:24:53 +01:00
|
|
|
count: 0,
|
2017-04-30 22:44:24 +02:00
|
|
|
}
|
|
|
|
|
2019-10-01 19:11:20 +02:00
|
|
|
const reducer = (state = initialState, action) => {
|
2016-12-22 06:10:54 +01:00
|
|
|
switch (action.type) {
|
2019-10-01 19:11:20 +02:00
|
|
|
case 'TICK':
|
|
|
|
return {
|
|
|
|
...state,
|
|
|
|
lastUpdate: action.lastUpdate,
|
2019-11-11 04:24:53 +01:00
|
|
|
light: !!action.light,
|
2019-10-01 19:11:20 +02:00
|
|
|
}
|
|
|
|
case 'INCREMENT':
|
|
|
|
return {
|
|
|
|
...state,
|
2019-11-11 04:24:53 +01:00
|
|
|
count: state.count + 1,
|
2019-10-01 19:11:20 +02:00
|
|
|
}
|
|
|
|
case 'DECREMENT':
|
|
|
|
return {
|
|
|
|
...state,
|
2019-11-11 04:24:53 +01:00
|
|
|
count: state.count - 1,
|
2019-10-01 19:11:20 +02:00
|
|
|
}
|
|
|
|
case 'RESET':
|
|
|
|
return {
|
|
|
|
...state,
|
2019-11-11 04:24:53 +01:00
|
|
|
count: initialState.count,
|
2019-10-01 19:11:20 +02:00
|
|
|
}
|
2018-12-17 17:34:32 +01:00
|
|
|
default:
|
|
|
|
return state
|
2016-12-22 06:10:54 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-05-28 07:12:27 +02:00
|
|
|
function initStore(preloadedState = initialState) {
|
2018-12-17 17:34:32 +01:00
|
|
|
return createStore(
|
|
|
|
reducer,
|
2019-10-01 19:11:20 +02:00
|
|
|
preloadedState,
|
2019-03-14 17:40:00 +01:00
|
|
|
composeWithDevTools(applyMiddleware())
|
2018-12-17 17:34:32 +01:00
|
|
|
)
|
2016-12-22 06:10:54 +01:00
|
|
|
}
|
2020-05-28 07:12:27 +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
|
|
|
|
}
|