Search code examples
javascriptreactjsredux

TypeError: state is not iterable on react and redux


So i just learned redux and tried to make a simple list with redux and react. but when i click on the button to add item to the list i got an error "state is not iterable"

here is my code

reducer


function manageList(state = { items: [] }, action) {
  switch (action.type) {
    case ADD_ITEM:
      return { list: [...state, action.payload] };
    case RESET_LIST:
      return {
        item: [...state, []],
      };
    default:
      return state;
  }
}

action

export const ADD_ITEM = "ADD_ITEM";
export const RESET_LIST = "RESET_LIST";

export function addItem(text) {
  return { type: ADD_ITEM, payload: text };
}

export function resetList() {
  return { type: RESET_LIST };
}

Solution

  • You're spreading an object inside an array, to fix that you should spread the items property inside an array:

    function manageList(state = { items: [] }, action) {
      switch (action.type) {
        case ADD_ITEM:
          return { list: [...state.items, action.payload] };
        case RESET_LIST:
          return {
            items: [...state.items, []],
          };
        default:
          return state;
      }
    }
    

    I think also that you should replace list and item by items :

    function manageList(state = { items: [] }, action) {
      switch (action.type) {
        case ADD_ITEM:
          return { items: [...state.items, action.payload] };
        case RESET_LIST:
          return {
            items: [...state.items, []],
          };
        default:
          return state;
      }
    }