I need to make changes in the "todo" element based on the "todoId" of the object. How can I do it? Like, if I want to change only the "todo" array of the object that has the "todoId" = 1, for example.
const [todoList, setTodoList] = useState([
{
todoId: 0,
todoName: "Personal",
todo: []
},
{
todoId: 1,
todoName: "Work",
todo: []
},
{
todoId: 2,
todoName: "College",
todo: []
},
])
5
Answers
You need to essentially recreate the whole array.
The updater function returned from the
useState
hook (setTodoList
in your case) can be used with either of the following:setTodoList([])
to set it to an empty array)The callback takes a single
prevState
argument which is just the previous state value. The callback should then return a new state value.This works great for array state variables since you will usually want to add/change/remove one item from the array.
Here’s something you could try:
or as a one-liner (functionally equivalent):
They can both be used like this:
You can create a function that receive the todoId and the todo data. and if finded the todo update the todo array.
Here is an example of how you could add and remove items from the various todo lists.
You will need to use the function callback version when setting the state. Just clone the lists, find the one you want to add to (or remove from), and return the modified clone. When clicking on a button, the DOM is queried for data attributes to identify which list or item you are modifying.
Note: In the example below, I just set a timestamp when adding a new item. You could modify this to show a dialog where you could enter the text of the todo item.
Also, avoid using
0
for an ID. In most languages zero could mean: false, unknown, null, nil, unset, or undefined. Starting with1
is preferred.Here’s a expanded example based on your data. The key section is in
handleClick
. After the section has been selected from the dropdown, the todo entered in the input box, and the button clicked……we update the
setTodoList
state by taking the previous state and mapping over it. If the section name equals the value of theselect
state we spread the existing section object into a new object (no mutation!). We spread the section’s todos array into a new array, adding in a new todo with an id (based on the current length of the todo array). We finally return the updated section object. If the section name and the select value don’t match we return the section object without changes.(Note, for this example, I’ve changed the property key names in the data to be a little more meaningful.)