0

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!)

Sreekar Mouli
  • 1,313
  • 5
  • 25
  • 49
  • Duplicate: [How to update nested state properties in React](https://stackoverflow.com/questions/43040721/how-to-update-nested-state-properties-in-react) –  Nov 09 '20 at 16:00
  • 1
    See the answers to [the linked question](https://stackoverflow.com/questions/39044135/update-array-in-react) (and several others :-) ) and [the React documentation](https://reactjs.org/docs/state-and-lifecycle.html#do-not-modify-state-directly). You can't directly modify an object held in state; instead, you have to create a **new** object, for instance: `const onInputChange = ({target: {name, value}}) => { setFormInputs(formInputs => ({...formInputs, [name]: value})); console.log("onInputChange => formInputs", formInputs); }; ` (https://pastebin.com/GDKNt8Zb) – T.J. Crowder Nov 09 '20 at 16:08
  • 1
    Here's the key to understanding why your code didn't work: https://jsfiddle.net/khrismuc/95nhm6zo/ –  Nov 09 '20 at 16:13

0 Answers0