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>
CodePudding user response:
Just initialize the values you want from inputs as empty strings;
const [inputs, setInputs] = useState({ firstName:"", lastName:"" });
CodePudding user response:
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));
},[]);