Update object with new changes that don't override unchanged values Vue.js 2

Viewed 607

I'm having an issue where a payload I'm receiving is not updating the values correctly for an object before passing it to the database. In other words, the new changes are not persisting for fields have new or changed values. I'm using Vue.js 2. How do I successfully update the incoming object and storing those values in an existing object with changes?

More information: We receive an object from an API that may have existing keys with values or none at all if the meeting matches certain characteristics - like the username/birthday/phone number. The form is supposed to pass the new key/values for the personal information if its changed. Instead of it doing that, the data is keeping the old changes and not updating the values for the new changes. userPersonalInfo is not updating in this case.

ModalVerification.vue

onVerifySuccess(existingData) {
 // if no object exist, complete new form 
 if(!Object.keys(existingData).length) {
   this.completeFormModal();
  } else {
   this.meetingDetails.is_authenticated_user = true;
   this.updateMeetPlanInformation(this.getMeetingPlanFields(existingData);

   // only return existing data if object not null // else update the existing data with new key/value pairs. Most likely wrong, because its not checking if any values in the object have been updated before passing.
   const userPersonalInfo = (existingData) === null ? this.getUserPersonalInfo(existingData) : existingData;

vueAssign(this.meetingDetails, userPersonalInfo);
this.completeFormModal();
}

export function vueAssign(objVal, srcVal) {
 Object.keys(srcVal).forEach((key) => {
   Vue.set(objVal, key, srcVal[key]);
 });
}
1 Answers

The problem is likely in vueAssign, but you haven't shown that method. I can still suggest solutions:

Object.assign

Use Object.assign to copy props from meetingDetails into userPersonalInfo, overwriting any common properties:

Object.assign(userPersonalInfo, this.meetingDetails)

const userPersonalInfo = {
  a: 1,
  b: 2,
}

const meetingDetails = {
  a: 999,
  c: 'hello',
}

Object.assign(userPersonalInfo, meetingDetails)

console.log({ userPersonalInfo })

Spread operator

Use the spread operator, which performs the same assignment:

let userPersonalInfo = /*...*/

userPersonalInfo = {
  ...userPersonalInfo,
  ...this.meetingDetails,
}

let userPersonalInfo = {
  a: 1,
  b: 2,
}

const meetingDetails = {
  a: 999,
  c: 'hello',
}

userPersonalInfo = {
  ...userPersonalInfo,
  ...meetingDetails,
}

console.log({ userPersonalInfo })

Related