update state to add element to array react usestate code example

Example 1: Updating an object with setState in React

this.setState(prevState => {
  let jasper = Object.assign({}, prevState.jasper);  // creating copy of state variable jasper
  jasper.name = 'someothername';                     // update the name property, assign a new value                 
  return { jasper };                                 // return new object jasper object
})

//2ND METHOD

this.setState(prevState => ({
    jasper: {                   // object that we want to update
        ...prevState.jasper,    // keep all other key-value pairs
        name: 'something'       // update the value of specific key
    }
}))

Example 2: how to set value in array react hook usestate

const[array,setArray]= useState([
        {id: 1, value: "a string", othervalue: ""},
        {id: 2, value: "another string", othervalue: ""},
        {id: 3, value: "a string", othervalue: ""},
    ])

const updateItem =(id, whichvalue, newvalue)=> {
  var index = array.findIndex(x=> x.id === id);

  let g = array[index]
  g[whichvalue] = newvalue
  if (index === -1){
    // handle error
    console.log('no match')
  }
  else
    setArray([
      ...array.slice(0,index),
      g,
      ...array.slice(index+1)
    ]
            );
}
//how to use the function    
onPress={()=>updateItem(2,'value','ewfwf')}
onPress={()=>updateItem(1,'othervalue','ewfwf')}
/*
the first input of the function is the id of the item
the second input of the function is the atrribute that you wish to change
the third input of the function is the new value for that attribute
It's a pleasure :0
~atlas
*/

Tags:

Misc Example