I have a piece of code in React, where if I use newArray = [... oldArray] it works, but if I use newArray = oldArray it doesn't. Can you tell me why?
Below the code. It's about adding a todo list when you click the Add button. So far it works. Then when you click on an item on the todo list, it should change class and become 'highlighted'. If I use newArray = oldArray, the state is correctly updated but then nothing changes on the screen:
const Todo = () => {
const [item, setItem] = useState('');
const [itemList, setItemList] = useState([]);
const onChange = (e) => {
setItem(e.target.value);
};
const handleClick = () => {
setItemList((prevState) => [
...prevState,
{ id: Math.random(), item: item, isDone: false },
]);
setItem('');
};
const handleItemClass = (i) => {
const updatedItemList = itemList;
updatedItemList[i].isDone = !updatedItemList[i].isDone;
setItemList(updatedItemList);
};
return (
<React.Fragment>
<div>
<input type="text" onChange={onChange} value={item} />
<button onClick={handleClick}>Add</button>
</div>
<p>
{itemList.filter((el) => el.isDone).length} completed from{' '}
{itemList.length}
</p>
<ul>
{itemList.map((itemCurrent, i) => (
<li
key={itemCurrent.id}
onClick={() => handleItemClass(i)}
className={itemCurrent.isDone ? 'is-done' : 'not-done'}
>
{itemCurrent.item}
</li>
))}
</ul>
</React.Fragment>
);
};
export default Todo;
render(<Todo />, document.getElementById('root'));