I have the following component where I display user's existing details in the inputs as values and user should be able to change those details and click save. But the issue is that it shows the following error in the console:
**index.js:1 Warning: A component is changing a controlled input of type text to be uncontrolled.**
Here is the component code:
const Settings = (props) => {
const { createUser, isAuthenticated, history, errors } = props;
const dispatch = useDispatch();
const authUser = useSelector(state => state.auth.user);
const [user, setUser] = useState({
data: {
name: "",
email: "",
password: "",
},
});
const [error, setError] = useState({
nameError: "",
emailError: "",
passwordError: "",
});
useEffect(() => {
setUser({
data: {
email:authUser.email,
}
});
}, [authUser]);
const { name, email, password } = user.data;
const { nameError, emailError, passwordError } = error;
const onUpdateUser = (e) => {
e.preventDefault();
const isValid = formValidator(user.data, setError);
if (isValid) {
dispatch(updateUser(user.data))
}
};
const onChange = (e) => {
const { name, value } = e.target;
const { data } = user;
setUser({
data: {
...data,
[name]: value,
},
});
};
return (
<BForm title="Create an account" handleSubmit={onUpdateUser}>
{errors ? <p className="error-feedback">{errors}</p> : ""}
<BInput
name="name"
type="text"
handleChange={onChange}
value={name}
placeholder="Your Name"
error={nameError}
/>
<BInput
name="email"
type="email"
handleChange={onChange}
value={email}
placeholder="Email"
error={emailError}
required
/>
<BInput
name="password"
type="password"
value={password}
handleChange={onChange}
placeholder="Password"
error={passwordError}
required
/>
<div className="buttons">
<BButton customClass="login-btn" isfullwidth={true} type="submit">
{" "}
Save{" "}
</BButton>
</div>
</BForm>
);
};
export default Settings;
What is wrong and how can be it fixed? I need to let see the existing values and then change whatever they want.