Home > Software engineering >  redux - how to remove element in array witch is nested to another array
redux - how to remove element in array witch is nested to another array

Time:10-03

I want to remove item by sending action "itemRemoved", to which I pass the id of the board and the id of the element to be deleted

How to edit my Reducer "case ITEM_REMOVED"?

Thanks.

const initialState = {
  boards: [
    {
      id: 1,
      title: "1",
      items: [
        { id: 1, title: "1" },
        { id: 2, title: "2" },
      ],
    },
    {
      id: 2,
      title: "2",
      items: [
        { id: 3, title: "3" },
        { id: 4, title: "4" },
        { id: 5, title: "5" },
      ],
    },
  ],
};

const actions = {
  itemRemoved: (boardId, itemId) =>
    ({ type: ITEM_REMOVED, boardId, itemId }),
}

const boardsReducer = (state = initialState, action) => {
  switch (action.type) {
    case ITEM_REMOVED:
      return {
        ...state,
        boards: [] // <-- ??????????
      };
    default:
      return state;
  }
};

CodePudding user response:

I'll try something like this:

const boardsReducer = (state = initialState, action) => {
  switch (action.type) {
    case ITEM_REMOVED:
      return {
        ...state,
        boards: state.boards.map(b => {
          if (b.id !== action.boardId) {
              return b
          }
   
          const newB = {...b}
          newB.items = newB.items.filter(i => i !== action.itemId)

          return newB;

        })
      };
    default:
      return state;
  }
};
  • Related