Vysp3r
Vysp3r

Reputation: 47

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:

 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>

Upvotes: 0

Views: 98

Answers (1)

Shan
Shan

Reputation: 1568

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.

For uncontrolled inputs we won't pass the value attribute. If we don't pass any attribute it is considered as undefined. Here you are confusing react by first setting it to undefined and later with some value. That's why you are getting changing from uncontrolled to controlled input warning.

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

Upvotes: 1

Related Questions