Previously, I have followed the system where I save each Input in a Form as a React state variable and have a common function to update them.
Now, I am trying to store all the Form data in a single object and store that as a React state variable (as follows).
const [formInputs, setFormInputs] = React.useState({});
const onInputChange = (event) => {
formInputs[event.target.name] = event.target.value;
setFormInputs(formInputs);
console.log("onInputChange => formInputs", formInputs);
};
And the Input elements are used as follows:
<input
type="text"
name="username"
placeholder="username"
value={formInputs.username || ""}
onChange={onInputChange}
/>
Here, the input element always stays empty even after entering data. Seems like the empty string ""
is always being considered rather than formInputs.username
from this condition: value={formInputs.username || ""}
By commenting out this line, it seems to be working. But, I don't think that's the proper way. Please suggest what I have missed here...
Code-Sandbox (Please check the Console
tab for the logs!)