0

I'm getting an error while controlling an input field which is : "A component is changing an uncontrolled input to be controlled. This is likely caused by the value changing from undefined to a defined value..." and when I try to write something in the input field, it gets back to the state value, here's my code for this

const [inputs, setInputs] = useState({});

useEffect(() => {
    Http.get(apiEndPoint, {
      params: {
        email: user.userEmail,
      },
    }).then((res) => setInputs(res.data));
  });

const handleChange = (e) => {
    setInputs((prevState) => ({
      ...prevState,
      [e.target.name]: e.target.value,
    }));
  };

These are two of the several input fields,

<Row>
               <Col className="pr-1" md="6">
                  <Form.Group>
                    <label>First Name</label>
                    <Form.Control
                      name="firstName"
                      onChange={handleChange}
                      type="text"
                      value={inputs.firstName || ""}
                    ></Form.Control>
                  </Form.Group>
                </Col>
                <Col className="pl-1" md="6">
                  <Form.Group>
                    <label>Last Name</label>
                    <Form.Control
                      name="lastName"
                      onChange={handleChange}
                      type="text"
                      value={inputs.lastName || ""}
                    ></Form.Control>
                  </Form.Group>
                </Col>
              </Row>
Saadi
  • 121
  • 1
  • 8
  • 1
    Your `useEffect` needs an empty array dependency: `useEffect(() => ...code, []);` so that it only gets called once when the component initially renders. Or if the component needs to fetch data when the state changes, add the state variable to the array instead. – Andy Sep 22 '21 at 08:03

2 Answers2

0

Just initialize the values you want from inputs as empty strings;

const [inputs, setInputs] = useState({ firstName:"", lastName:"" });
İlker
  • 1,872
  • 1
  • 12
  • 28
  • oh my bad, I forgot to share the useEffect where I'm setting the useState, let me edit this question – Saadi Sep 22 '21 at 07:55
  • well, that should still work – İlker Sep 22 '21 at 07:59
  • yes, it should work, what is happening now is whenever I try to type something in the input field, the field gets reset to its initial value, like the value I'm setting in the useEffect – Saadi Sep 22 '21 at 08:04
0

Have useEffect triggered during initial rendering. Then it won't be triggered every re-render and change the state to its initial values.

useEffect(() => {
    Http.get(apiEndPoint, {
      params: {
        email: user.userEmail,
      },
    }).then((res) => setInputs(res.data));
  },[]);
Kavindu Vindika
  • 2,449
  • 1
  • 13
  • 20