1

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 :

  1. Creating a todo list within React.
  2. My state consists of an array labeled itemsArr with each array element being an object
  3. The objects initialize with the following format :
    • { complete : false, item : "user entered string", id : uuid(), }
  4. Upon clicking a line item, I am calling a function handleComplete in order to strikethrough the text of that line by toggling complete : false/true
  5. 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 })
    }

3 Answers 3

4

In both snippets you haven't correctly returned a new object from the .map callback:

 handleComplete(id){
  const newItemsArr = this.state.itemsArr.map(obj => 
     obj.id === id ? { id: obj.id, complete: !obj.complete } : obj);
  this.setState({ itemsArr : newItemsArr });
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, so you always need to rebuild the whole object?
Yes, state shall be immutable. So whenever you mutate, copy.
1

Your function, as mentioned above, returns and updates wrong data, by adding new elements in your state instead of updating your current array.

Since array.map() returns an array, you can assign it to the state array, itemsArr.

You should also replace the change condition by updating the element's value first, and then returning it, if its id matches,or else, simply leave it as is.

handleComplete=(id)=>{
      this.setState(state =>{
        itemsArr:state.itemsArr.map(obj => obj.id === id 
                                 ? (obj.complete = !obj.complete,obj) //update element's complete status and then return it
                                 : obj) //return element as is
      },()=>console.log(this.state.itemsArr)) //check new state
    }

live example using your data : https://codepen.io/Kalovelo/pen/KKwyMGe

Hope it helps!

Comments

0
state = {
    itemsArr: [
        {
            complete: false,
            item: 'iemName',
            id: 1
        },
        {
            complete: false,
            item: 'iemName',
            id: 2
        }
    ]
}

handleComplete = (id) => {
   let { itemsArr } = { ...this.state };
   itemIndex = itemsArr.findIndex(item => id === item.id);
   itemsArr[itemIndex]['complete'] = !itemsArr[itemIndex]['complete'];
   this.setState{itemsArr}
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.