usestate object hooks 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: 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 3: when to use previous state in useState
import React, { useState } from "react";
import ReactDOM from "react-dom";
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<h1>{count}</h1>
<button onClick={() => setTimeout(() => setCount(count + 1), 2000)}>
Delayed Counter (basic)
</button>
<button onClick={() => setTimeout(() => setCount(x => x + 1), 2000)}>
Delayed Counter (functional)
</button>
<button onClick={() => setCount(count + 1)}>Immediate Counter</button>
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<Counter />, rootElement);