Skip to content
Advertisement

Need Help Figuring Out State in React

I’m working on a basic Todo app. I’m storing the todo items in state as an array of objects. The object key is the todo item, the value is either true(done) or false(not done). When I click a button to check off an item, I want to change the value of the todo item as well as change the style of the element to indicate it is done.

this.state = {items: [...{"todo item": false}]}

handleClick(e, item, index){
        e.preventDefault()
        let newState = [...this.state.items];
        if(this.state.items[index][Object.keys(item)] == false){
            //blue = done
            e.target.parentNode.style.color = 'blue';
            newState[index][Object.keys(item)] = true;
        }
        this.setState({items:newState})
        console.log(this.state.items[index])
}

This is not working. I’m assuming that it is because setState is asynchronous. I thought to try it this way because I want to send my state object to my database so I can keep track of the “doneness” of each item. I don’t want to remove the item from my items array. Any help would be very much appreciated. Let me know if more information is needed!

Advertisement

Answer

I don’t think setState is the issue here? The issue is how you modify the color.

For the color, I would use a ternary based off the state variable rather than DOM manipulation. Something like this answer: ternary operator in jsx to include html with react

If the state isn’t uploading (log it at the start of the function so you can see what it is after the run rather than immediately after), then that’s a separate issue.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement