1

I am building a simple application with reactjs, redux; The database like this

const initialState = [
  {
    title: "List 1",
    id: 0,
    cards: [
      {
        id: 0,
        text: "Task 1",
      },
      {
        id: 1,
        text: "Task 2",
      },
    ],
  },
  {
    title: "List 2",
    id: 1,
    cards: [
      {
        id: 0,
        text: "Task 3",
      },
      {
        id: 1,
        text: "Task 4",
      },
    ],
  },
];

The app has many lists. In many list has many cards, I want delete a card in a list So in my listReducer.js. I created a delete reducer to delete a task like this.

case CONSTANTS.DELETE_CARD: {
      const { listId, id } = action.payload;
      return state.map((list) => {
        if (list.id === listId) {
          return {
            ...list,
            cards: list.cards.filter((card) => card.id !== id),
          };
        }
        return list;
      });
    }

But It not working correctly. What I am doing wrong?

the code: https://codesandbox.io/s/github/htactive-nhaptt/crud-trello?file=/src/reducers/listReducers.js:1466-1773

1 Answer 1

4

The issue is not with your reducer. I looked at your codesandbox example and added a few console.log and looks like everything gets updated correctly.

The problem is in the render function of your List component in components/List.js. Because you're not passing a unique key to Card component, React doesn't know what items have changed and it only sees a change in cards list lenght. So on re-render, it renders the old list up to the new length (hope it makes sense!) See here for more info on keys: https://reactjs.org/docs/lists-and-keys.html#keys.

You can fix the issue by passing a unique key to Card like this on line 72:

return <Card key={card.id} id={card.id} listId={listId} text={card.text} />;

Sign up to request clarification or add additional context in comments.

1 Comment

You beat me ;-) so I upvote yours....but I think there is still a problem in his reducer : he is mutate it directly

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.