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.

2
  • 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' Commented May 4, 2023 at 21:06
  • See also stackoverflow.com/questions/679915/… and developer.mozilla.org/en-US/docs/Glossary/Truthy Commented May 4, 2023 at 21:08

1 Answer 1

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>
        )}
Sign up to request clarification or add additional context in comments.

3 Comments

@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.. /:
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
Cool! Make sure you still apply the above fixes too :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.