I'm getting data for a Vacation object from mySQL server with axios. I console log the response.data and I see the object as needed. for some reason, I cant populate the form inputs with the data I get.
const [editedVacation, setEditedVacation] = useState<Vacation>(
{} as Vacation
);
useEffect(() => {
const getVacation = async () => {
try {
const response = await axios.get<Vacation>(
`http://localhost:4000/api/v1/vacations/list/${id}`
);
setEditedVacation(response.data);
console.log(response.data);
} catch (error) {
console.log(error);
}
};
getVacation();
}, [id]);
This is the form itself (please note in here I posted the 'destination' part of the form, because its a really long one.) Also, I'm rendering the form only of editedVacation isn't null / undefined, to make sure the data is there.
{editedVacation && (
<form className="editVacationForm" onSubmit={handleSubmit(onSubmit)}>
<Typography variant="h4">
Edit Vacation{" "}
<FontAwesomeIcon icon={faUmbrellaBeach} color="#FFC857" />
</Typography>
<TextField
defaultValue={editedVacation.destination}
className="destination"
type="text"
label="Destination"
{...register("destination")}
error={!!errors.destination}
helperText={errors.destination?.message}
onBlur={() => trigger("destination")}
/>
</form>
)}
Thanks a lot.
Two issues. Firstly you say:
This is not true since your default value is
{}which is truthy, so youreditedVacation && (check will pass even before the data is returned.Secondly, you are using
defaultValuebut should be usingvalue. The former is for uncontrolled inputs, you want controlled here since the state is managed in this parent component.