usestate with object code example
Example 1: update object in react hooks
- Through Input
const [state, setState] = useState({ fName: "", lName: "" });
const handleChange = e => {
const { name, value } = e.target;
setState(prevState => ({
...prevState,
[name]: value
}));
};
<input
value={state.fName}
type="text"
onChange={handleChange}
name="fName"
/>
<input
value={state.lName}
type="text"
onChange={handleChange}
name="lName"
/>
***************************
- Through onSubmit or button click
setState(prevState => ({
...prevState,
fName: 'your updated value here'
}));
Example 2: react usestate
import React, { useState } from 'react';
function Example() {
// Declare a new state variable, which we'll call "count"
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
Example 3: prevstate in usestate
const [prevState, setState] = React.useState([]);
setState(prevState => [...prevState, 'somedata'] );
Example 4: 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)
}
Example 5: update state in useState hook
// declare state using useState hook.
// someState is set to someInitialState
const [someState, setSomeState] = useState(someInitialState);
// setSomeState updates the current state
setSomeState(someOtherState);