react native setstate usestate nested object code example
Example 1: access nested state value in hookstate
// However, there is a nested state method, which allows to access nested state by name.
// example :-
state = {
user: {
name: { firstName: 'Kaushal', lastName: 'Shah' }
}
};
// To access state =>
state
// To access user =>
state.user or state.nested('user')
// To access name =>
state.user.nested('name')
// To access firstName =>
state.user.nested('name').nested('firstName')
Example 2: 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)
}