Goal :
Within a React App, understand how to correctly update a boolean value that is stored within an array in state.
Question :
I am not sure if my code is correct in order to avoid asynchronous errors (whether or not it works in this case I am not interested in as my goal is to understand how to avoid those errors in all cases). Is there some syntax that is missing in order to correctly create a new state?
Context :
- Creating a todo list within React.
- My state consists of an array labeled
itemsArrwith each array element being an object - The objects initialize with the following format :
{ complete : false, item : "user entered string", id : uuid(), }
- Upon clicking a line item, I am calling a function
handleCompletein order to strikethrough the text of that line by togglingcomplete : false/true - The function is updating state via this :
handleComplete(id){
this.setState(state =>
state.itemsArr.map(obj => obj.id === id ? obj.complete = !obj.complete : '')
)
}
Additional Details :
One of my attempts (does not work) :
handleComplete(id){
const newItemsArr = this.state.itemsArr.map(obj =>
obj.id === id ? obj.complete = !obj.complete : obj);
this.setState({ itemsArr : newItemsArr })
}