Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

React.js controlled components using nested states

The problem:
How can I update the nested states from [data] from my form without any errors. The way I’m doing it right now works, but it throws me an error in the console. What is the correct way to update a nested state from a form.

I know that data is initialized empty and it’s simply because it is set when the page load with useEffect.

The code:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

 const [data, setData] = useState({});

    <Form.Group className="mb-3">
        <Form.Label>Title</Form.Label>
        <Form.Control
            required
            placeholder="Enter title"
            value={data?.title}
            onChange={(e) => setData({...data, title: e.target.value})}
        />
        {formError?.title?.length > 0 ? <Form.Label className="text-danger">{formError?.title}</Form.Label> : null}
    </Form.Group>

>Solution :

React will treat this as uncontrolled component, because the value attribute is undefined initially and you are setting it to string on Change of value.

Provide default value in state to use it as a controlled input.

const [data, setData] = useState({title: ""});

or value={data?.title || ""}

See more of controlled/uncontrolled components

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading