Paul Strutinsky
Paul Strutinsky

Reputation: 23

How can I return the state correctly in my Redux app?

We have some todo list. We have initialState kind of of like...

initialState = [   {
  id: 0,
  title: "first",
  items: [
    {
      title: "one from first",
      id: 0,
      cards: [
        {
          id: 0,
          text: "111",
        },
        {
          id: 1,
          text: "222",
        },
      ],
    },
    {
      title: "two from first",
      id: 1,
      cards: [
        {
          id: 0,
          text: "www",
        },
        {
          id: 1,
          text: "zzz",
        },
      ],
    },
  ],   },   {
    id: 1,
    title: "second board",
    items: [
      {
        title: "first from second",
        id: 0,
        cards: [
          {
            id: 0,
            text: "asd",
          },
          {
            id: 1,
            text: "fasdf",
          },
        ],
      },
    ],   }, ];

We wont normalize this state for some reasons. I have to add new List. The reducer here:

switch(action) {
  case CONSTANTS.ADD_LIST:
    const newList = {
      title: action.payload.title,
      cards: [],
      id: listID,
    };
    listID += 1;

    return {
      ...state,
      [action.payload.boardID]: {
        ...state[action.payload.boardID],
        items: [...state[action.payload.boardID].items, newList],
      },
    };
}

Example. I want to add newList for items from board 1(starting from 0).

I tested another examples like the above and it's useless.

So I can't get why it's not working. I think I have some problems with docs redux and I can't get it.

Thanks!

Upvotes: 2

Views: 49

Answers (1)

nishkaush
nishkaush

Reputation: 1548

Your initialState seems to be an Array and not an object:

initialState = [ {Board1},{Board2} ]

But your reducer seems to be returning an object, so perhaps thats a potential issue.

======

You could instead try the following changes in your reducer:

  • make shallow copy of boardsArr aka initialState
  • loop over each board and create a new board object
  • Loop over each board object's items prop, and create its shallow copy
  • loop each item's cards prop and create its copy
  • finally replace the board's items you want and then
  • return the newly created boardsArr
// Pseudo code inside reducer

const newBoardsArr = state.map(board => {
    return {
        ...board,
        items: board.items.map(item => ({
            ...item,
            cards: item.cards.map(card => ({
                ...card
            }))
        }))
    }
});

// lets say we want to update first board's items, then:

newBoardsArr[action.payload.boardID].items = newList;
return newBoardsArr;

Upvotes: 1

Related Questions