I have a reactjs form, on page load it will show all values from database which user can change and submit. When I am trying to change input value, it updates state but not UI.
Below is the sample code. My form has many input controls.
const [user, setUser] = useState({});
useEffect(() => {
//calling api and update state on page load
setUser(response);
}, [])
const handleChange= (e)=>{
let track= user;
track[e.target.name]=e.target.value;
setUser(track);
}
//HTML CODE
<form name='NewUser'>
<table>
<tr>
<td>
<input
className="form-control"
name="firstInput"
onChange={handleChange}
type="number"
min="0"
max="1000"
value={user.firstInput}
/>
</td>
<td>
<input
className="form-control"
name="secondInput"
onChange={handleChange}
type="number"
min="0"
max="1000"
value={user.secondInput}
/>
</td>
<tr/>
</table>
</form>
CodePudding user response:
You are mutating the state object! You are also not providing a new object reference for the React state. React is bailing out of rerenders since the state reference never updates.
const handleChange= (e) => {
let track= user; // <-- track is reference to state
track[e.target.name]=e.target.value; // <-- state mutation!
setUser(track); // <-- save state reference back into state
}
You need to create a new state object, then update. Use a functional state update to access the previous user state and shallow copy it into a new object reference, and update the specified property by the dynamic key.
const handleChange= (e) => {
setUser(user => ({
...user,
[e.target.name]: e.target.value
}));
}