简体   繁体   中英

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

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

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!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM