Answers for "why use state with arry"

3

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
*/
Posted by: Guest on August-21-2020
1

usestate nested object

const [currentApp, setCurrentApp] = useState({
        userID: null,
        hospitalName: null, 
        hospitalID: null,
        date: null,
        time: null,
        timestamp: null,
        slots: 1,
        appointmentType: null
    })
    
const [appointmentType, setAppointmentType] =  useState({
        Granulocytes: {
            bloodType:null,
            message: null
        }
})

const handleGranChange = (e) => {
        setAppointmentType({...appointmentType, Granulocytes : {
            ...appointmentType.Granulocytes, 
            [e.target.id] : e.target.value}
        })
		setCurrentApp({ ...currentApp, ['appointmentType'] : appointmentType  })
        console.log(currentApp)
}
Posted by: Guest on July-06-2020

Code answers related to "Javascript"

Browse Popular Code Answers by Language