1

I am using Vue3 composition API and tried resetting the form with the help of Object.assign. Unfortunately, it doesn't reset the form when there are nested properties.

const initialForm = {
    name: "",
    details: {
        type: ""
    }
};

const form = reactive({ ...initialForm });

const resetForm = () => {
    Object.assign(form, initialForm);
}

Here name is reset but details.type is not reset. What should be the approach to reset form here?

1 Answer 1

1

spread operator ... and Object.assign they do shallow copy ONLY.

which means it does not change nested refernces. so details.type from initialForm is the same used in form.details.type.

for that you need to deep copy / clone the object when assigning to form. also when you do the resetForm.

using https://lodash.com/docs/4.17.15#cloneDeep

const initialForm = {
    name: "",
    details: {
        type: ""
    }
};

let form = reactive( _.cloneDeep(initialForm));

const resetForm = () => {
    form =  _.cloneDeep(initialForm) ;
}

without external package:

const initialForm = {
    name: "",
    details: {
        type: ""
    }
};

let form = {...initialForm, details : {...initialForm.details} } ;

const resetForm = () => {
    form = {...initialForm, details : {...initialForm.details} } ;
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.