rsnext/examples/with-redux-wrapper/store/store.js

38 lines
1.1 KiB
JavaScript
Raw Normal View History

import { createStore, applyMiddleware, combineReducers } from 'redux'
import { HYDRATE, createWrapper } from 'next-redux-wrapper'
import thunkMiddleware from 'redux-thunk'
import count from './count/reducer'
import tick from './tick/reducer'
2020-05-18 21:24:37 +02:00
const bindMiddleware = (middleware) => {
if (process.env.NODE_ENV !== 'production') {
const { composeWithDevTools } = require('redux-devtools-extension')
return composeWithDevTools(applyMiddleware(...middleware))
}
return applyMiddleware(...middleware)
}
const combinedReducer = combineReducers({
count,
tick,
})
const reducer = (state, action) => {
if (action.type === HYDRATE) {
const nextState = {
...state, // use previous state
...action.payload, // apply delta from hydration
}
if (state.count.count) nextState.count.count = state.count.count // preserve count value on client side navigation
return nextState
} else {
return combinedReducer(state, action)
}
}
const initStore = () => {
return createStore(reducer, bindMiddleware([thunkMiddleware]))
}
export const wrapper = createWrapper(initStore)