0
const data = [
  {
    title: 'Todo',
    items: ['do home work', 'complete study'],
  },
  {
    title: 'In-Progress',
    items: ['learn tailwind', 'build some projects'],
  },
  {
    title: 'Completed',
    items: ['completed work'],
  },
];



const [list, setList] = useState(data);

const [text, setText] = useState('');

This addItem function adding a new copy of Todo every time when I add an item. How can I add the item to the todo without adding a new copy

const addItem = () => {
    setList((prev) => {
      return [
        (prev[0] = {
          ...prev[0],
          items: [text, ...prev[0].items],
        }),
        ...prev,
      ];
    });

    setText('');
};

enter image description here

1
  • You should have some id for find to which todo add a new item. Like addItem = (text, todoId). Commented Jul 25, 2021 at 13:35

2 Answers 2

1

This is some problematic design choice since you assuming your todos object is always first item in the array (prev[0]), but going straight forward is:

const addItem = () => {
  setList((prev) => {
    const [todoData, ...rest] = prev;
    return [{ ...todoData, items: [...todoData.items, text] }, ...rest];
  });

  setText("");
};
Sign up to request clarification or add additional context in comments.

Comments

0

You need to create a new object, this is how react works.

React compares the previous state and the new state, then decides to is there a need to re-render the component. And React uses referential equality. If you just keep using the same object by modifying it, then React will think that no need to re-render the component because of the state object is always the same.

So, you should keep creating a new instance like the following..

const addItem = (item) => {
    setList((prev) => {
      return {
      ...prev,
      item
      }
    });

    setText('');
};

Comments

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.