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]);
1
  • 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 :) Commented May 25, 2021 at 10:16

1 Answer 1

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]);

Sign up to request clarification or add additional context in comments.

5 Comments

Object.assign doesn't do a deep copy, it doesn't go deeper than the first level, unlike helpers like cloneDeep
Thank you, I changed solution to JSON.parse(JSON.stringify())
@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]),
@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!
@PiotrO Good luck!

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.