Home > Software design >  How does a complete check function work in ReactJs?
How does a complete check function work in ReactJs?

Time:09-26

I'm making a todo list and I don't really understand this whole complete check function, like where does the item come from and so...can anybody help me to explain! Thank you so much for helping me!

This is the function:

const handleComplete = (todo) => {
    setTodos(
        todos.map((item) => {
            if(item.id === todo.id){
                return {...item, completed: !item.completed}
            }
            return item
        })
    )
}

CodePudding user response:

The Array.prototype.map() is a function that creates and returns a new array filled with elements being the results of the function called on each element on the array:

//[array] [element]     [transformed  element inserted in result array]
//  |        |                               |
//  v        v                               v
todos.map((item) => ({...item, completed: !item.completed}));

So whatever your todos array holds as items, the returned result that will be passed as an argument to setTodos will be an array of {...item, completed: !item.completed} elements each.

You can read more about the Array.prototype.map() function in the MDN documentation.

Note that this is pure Javascript and has nothing to do with React or any other framework / library.

CodePudding user response:

As Your code suggests, you are trying to update a single item from your list of todos elements, so when your handleComplete function is called, a todo object is passed, so in the setTodos function, with the help of the map first we find the item from collection of todos which matches with id of passed todo object.

If found, we will return an object, ...item it helps to preserve all the elements present in the item object and only update the complete key.

CodePudding user response:

todos is an array and every array has a map function which iterates on the array and is used to modify the items in a array. So item is representing the current item of the array. You can name it anything.

In this function , you are setting the state of todos using the setTodos. Here we are checking that if item.id is equal to todo.id then set the state of todos.

And while setting the state , we are preserving the initial state of todos by using this return {...item, completed: !item.completed}

Three dots before item is called destructuring.

Destructuring assignments

Map function

  • Related