I came up with the following questing while I was trying to make a TODO app using React.js I was trying to make and update functionality for each task. For that, I made a button which on click, calls a function "update" which calls a function passed as a prop defined in App.js, this function iterates through the tasks array find the one to modify and does its thing, then it sets the new state
App.js
function App() {
const [taskItems, settaskItems] = useState([]);
const updateTask = (task,newname) =>{
const findAndModify=()=>{
let tasks = [...taskItems] // Why let task=taskItems doesnt work?
for (let index = 0; index < tasks.length; index++) {
const t = tasks[index];
if (t.name === task.name){
t.name = newname
}
}
return tasks
}
settaskItems(findAndModify())
}
}
My TaskRow component is the following
<TaskRow task={task} key={task.id} toggleTask={toggleTask} updateTask={updateTask}></TaskRow>
Inside the definition of my TaskRow.js component I have the following code
export const TaskRow = (props) => {
const update = () => {
const newname = "hello";
props.updateTask(props.task, newname);
};
return (
<tr key={props.task.id}>
<td>{props.task.name}</td>
<td>
<input
type="checkbox"
checked={props.task.done}
onChange={() => props.toggleTask(props.task)}
/>
</td>
<td>
<button className="btn btn-success mx-1" onClick={update}>
Actualizar
</button>
</td>
</tr>
);
};
the question comes here, if in findAndModify instead of doing let tasks = [...taskItems] I do task=taskItems the description of the updated task does not re-render until another change happens, but if a do a console.log of the data, it indeed, had been modified why is that? how does the [...] operator differs of a regular variable assignment? I've researched about destructuring in JS but nobody talks about some kind of difference between the use of this operator and a regular var assignment in React.js