How can I update an existing React object item?

The update works! But? A new empty item is added. Does anyone know the solution to this? Sorry I'm inexperienced with React.

Here are the codes and screenshots;

to-do-list.js

<Button onClick={() => props.updateTask(data.id)} size="small" color="primary">Mark Completed</Button>

App.js

const handleUpdateTask = (id) => {
    setTodos((previousData =>
        [
            ...previousData,
            todos[id]["title"] = "update?"
        ]
    ))
}

Before clicking; enter image description here

And After clicking; enter image description here

Upvotes: 0

Views: 48

Answers (1)

DSPdav
DSPdav

Reputation: 170

are you use useState hook? if yes, how about this:

const handleUpdateTask = (id) => {
    setTodos(todos.map(todo => todo.id === id ? {...todo, completed: true} : todo);
}

in code above, insted we acces index we utilize id property in each todo in todos array of object. than, we update its completed property. Hope this could help.

Upvotes: 1

Related Questions