KamiFightingSpirit
KamiFightingSpirit

Reputation: 55

Updating Boolean Value in React State Array

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 })
    }

Upvotes: 1

Views: 7823

Answers (3)

Kalovelo
Kalovelo

Reputation: 51

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!

Upvotes: 1

Abhijit Sil
Abhijit Sil

Reputation: 191

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}
}

Upvotes: 0

Jonas Wilms
Jonas Wilms

Reputation: 138267

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 });
}

Upvotes: 4

Related Questions