0

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.

DanWi
  • 50
  • 5
  • Except you're only checking for "truthy" and you initialized editedVacation to an empty object. Which is true. I think you want to init it to undefined. You can see a very simple example of this by looking at devtools and typing `let r = {}; r && 'hi'` vs `let x = undefined; x && 'hi'` – Nikki9696 May 04 '23 at 21:06
  • See also https://stackoverflow.com/questions/679915/how-do-i-test-for-an-empty-javascript-object and https://developer.mozilla.org/en-US/docs/Glossary/Truthy – Nikki9696 May 04 '23 at 21:08

1 Answers1

0

Two issues. Firstly you say:

Also, I'm rendering the form only of editedVacation isn't null / undefined, to make sure the data is there.

This is not true since your default value is {} which is truthy, so your editedVacation && ( check will pass even before the data is returned.

Secondly, you are using defaultValue but should be using value. The former is for uncontrolled inputs, you want controlled here since the state is managed in this parent component.

 const [editedVacation, setEditedVacation] = useState<Vacation | null>(
    null
  );
 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]);
    {editedVacation && (
          <form className="editVacationForm" onSubmit={handleSubmit(onSubmit)}>
            <Typography variant="h4">
              Edit Vacation{" "}
              <FontAwesomeIcon icon={faUmbrellaBeach} color="#FFC857" />
            </Typography>
            <TextField
              value={editedVacation.destination}
              className="destination"
              type="text"
              label="Destination"
              {...register("destination")}
              error={!!errors.destination}
              helperText={errors.destination?.message}
              onBlur={() => trigger("destination")}
            />
       
          </form>
        )}
adsy
  • 8,531
  • 2
  • 20
  • 31
  • @asdy I'm afraid this doesn't work as well, although I do realize that when I pass ({}) as the initial state results in a truthy value rather than null. I've tried changing to null to begin with, but still the data won't populate the inputs.. /: – DanWi May 05 '23 at 04:52
  • I found the issue, its quite stupid. my backend returns an array of objects (in this case just one object). once I say setEditedVacation(response.data[0]) - it works. Thanks for the help guys – DanWi May 05 '23 at 07:27
  • Cool! Make sure you still apply the above fixes too :) – adsy May 05 '23 at 09:14