0

I'm trying to set the default values I'm receiving from the API. Everything works fine except the nested object values - email and phone

In general form works well when I'm typing the values and submitting them, but not the other way around.

const { name, description, contact } = fetchedData;
const { email, phone } = contact;

const { reset } = useForm({
    mode: "onChange",
    defaultValues: {
      name,
      description,
      contact: {
        email,
        phone,
      }
    }
})

useEffect(() => {
    reset({
      name,
      description,
      contact: {
        email,
        phone,
      }
    });
}, [fetchedData]);
Piotr O
  • 427
  • 1
  • 5
  • 16
  • Can You add some info about `reset` function? What does this function do? On the first look - I think that problem with destructurization of an object. Better use `Object.assign()`. If you will provide more info i will probably answer better :) – KletskovG May 25 '21 at 10:16

1 Answers1

1

Probably it can problem with destructurization of an object. Destructurization dont do deep copy of an object, that why deep fields not copied.

You can try to create a copy with JSON.parse(JSON.stringify()) and pass it to reset function.

useEffect(() => {
    const deepCopy = JSON.parse(JSON.stringify({ 
        name,
        description,
        contact: { 
          email, 
          phone,
        }
      }
    ))
    reset(deepCopy);
}, [fetchedData]);
KletskovG
  • 520
  • 4
  • 10
  • 2
    Object.assign doesn't do a deep copy, it doesn't go deeper than the first level, unlike helpers like [cloneDeep](https://lodash.com/docs/4.17.15#cloneDeep) – Nino Filiu May 25 '21 at 10:30
  • 1
    Thank you, I changed solution to `JSON.parse(JSON.stringify())` – KletskovG May 25 '21 at 10:37
  • @KletskovG unfortunately no luck, I tried to use `useMemo` hook to set the default values as there is some work around with it, but still no luck `defaultValues: useMemo(() => deepCopy || {}, [deepCopy]),` – Piotr O May 25 '21 at 10:42
  • 1
    @KletskovG verified the code and there was some additional issue not related to the deep copy. Looks like your suggested solution works as expected. Many thanks! – Piotr O May 25 '21 at 13:08
  • @PiotrO Good luck! – KletskovG May 25 '21 at 13:37