Search code examples
javascriptreactjsreduxreact-redux

How to handle undefined as API response when using spread operator?


I'm using react and context: When I fetch items and there is no data, I send null. null becomes undefined (within res.send). In my reducer, I use spread operator when new items are being added. That results in an err as I'm trying to spread undefined (when there is no items yet and later added its first undefined).

What is good practice and what should I do in this case to change undefined into an empty array or so? Thank you

const initialState = {
  isFetchingItems: null,
  items: [],
  fetchErrorMessage: null
}
const reducer = (state, action) => {
  switch (action.type) {
    case 'FETCH_ITEMS':
      return {
        ...state,
        isFetching: true
      }
    case 'FETCH_ITEMS_SUCCESS':
      return {
        ...state,
        items: action.payload.messages,
        isFetching: false
      }
    case 'FETCH_ITEMS_ERROR':
      return {
        ...state,
        fetchErrorMessage: action.payload,
        isFetching: false
      }
    case 'ADD_ITEMS_SUCCESS':
      return {
        ...state,
        items: [action.payload, ...state.items] // here the err comes from as its like [action.payload, ...undefined]
      }
    default:
      return state;
  }
};

My action:

const fetchItems = async() => {
  dispatch({ type: 'FETCH_ITEMS' })
  try {
    let items = await API.fetchItems();
    dispatch({ type: 'FETCH_Items_SUCCESS', payload: items })
  } catch (error) {
    dispatch({ type: 'FETCH_ITEMS_ERROR', payload: error.message })
  }
};

const fetchItems = async() => {
  // ...
  dispatch({ type: 'ADD_ITEMS_SUCCESS', payload: items })
  // ...
}

Solution

  • You may use nullish coalescing for simple and concise fallback behavior:

    [action.payload, ...(state.items ?? [])]
    

    If state.items is null or undefined, [] will be used instead of state.items. Otherwise, it's going to use state.items.