react-redux-starter-kit icon indicating copy to clipboard operation
react-redux-starter-kit copied to clipboard

Initial state from server overridden by async route

Open piu130 opened this issue 8 years ago • 0 comments

The initial state from server is overridden by reducers initial state if server is faster than fetch route.

Example Counter/index.js:

import { loadInitialState } from './modules/counter'
export default (store) => ({
  ...
  onEnter (nextState, replace) {
    loadInitialState(store) // load initial state on enter route
  }
})

Counter/modules/counter.js:

export const LOAD_INITIAL_COUNTER_STATE = 'LOAD_INITIAL_COUNTER_STATE'
...
export const loadInitialState = (store) => {
  const { dispatch } = store
  return new Promise((resolve) => {
    setTimeout(() => {
      dispatch({
        type    : LOAD_INITIAL_COUNTER_STATE,
        payload : 3 // expected initial state
      })
      resolve()
    }, 20) // this must be smaller than time to fetch route
  })
}
...
const ACTION_HANDLERS = {
  ...
  [LOAD_INITIAL_COUNTER_STATE]: (state, action) => action.payload
}
...
const initialState = 0 // actual initial state
...

How can I fix this?

piu130 avatar Feb 05 '17 13:02 piu130