0
votes

When I dispatch an action after dispatching another action, I noticed that my state isFetching becomes undefined. I think it's probably some asynchronous issue with the actions dispatching after the other. How would I fix this so that I can get both actions to dispatch correctly?

My redux module:

const FETCHING = 'FETCHING'
const FETCHING_KEYWORD = 'FETCHING_KEYWORD'

function fetching() {
  return {
    type: FETCHING,
  }
}

function settingKeyWord(keyWord) {
  return {
    type: FETCHING_KEYWORD,
    keyWord,
  }
}

export function fetchKeyWord (keyWord) {
  return (dispatch, getState) => {
    const { isFetching } = getState()
    const { keyWord } = getState()

    // After I dispatch the two actions here, isFetching becomes undefined
    dispatch(fetching())
    dispatch(settingKeyWord(keyWord))
  }
}

const initialState = {
  isFetching: false,
  keyWord: '',
}

export default function results(state = initialState, action) {
  switch (action.type) {
    case FETCHING:
      return {
        isFetching: true,
      }
    case FETCHING_KEYWORD:
      return {
        keyWord: action.keyWord,
      }
    default:
      return state
  }
}
1

1 Answers

1
votes

The reducer cases need to return the entire state, not just the updated part, so the problem should also occur when dispatching either action normally. You can fix it by using Object.assign or object-spread syntax in the reducer cases. For example, for Fetching:

case FETCHING:
  return Object.assign((), state, { 
    isFetching: true,
  })

or

case FETCHING:
  return {...state,
    isFetching: true,
  })