I want to refactor the Vue component where the same data comes in different structures.
Example Appointment.vue component:
<template>
<div>
<div v-if="config.data.user.user_id">
{{ config.data.user.user_id }}
</div>
<div v-if="config.data.user.address.full_address">
{{ config.data.user.address.full_address }}
</div>
.
.
.
</div>
</template>
<script>
export default {
name: 'appointment',
props: {
config: {
required: true,
},
},
// Some operations uses 'config' prop
//.
//.
//.
}
</script>
In CreateAppointment.vue component that uses Apponintment.vue:
<template>
<div>
<appointment :config="data"/>
.
.
.
</div>
</template>
<script>
export default {
name: 'Create Appointment',
data() {
return {
data: null,
};
},
methods: {
openAppointment() {
const result = // api get operation that returns object which I'll use on Appointment.vue
if (result) {
const temp = {
user: null,
}
temp.appointment_id = result.appointment_id;
.
.
.
temp.user.user_id = result.user_profile.user_id;
.
.
.
this.data = { ...temp };
}
}
}
}
</script>
In AppointmentList.vue which uses Appointment.vue:
<template>
<div>
<appointment :config="data"/>
.
.
.
</div>
</template>
<script>
export default {
name: 'AppointmentList',
data() {
return {
data: null,
};
},
methods: {
openAppointment() {
const result = // api get operation that returns object which I'll use on Appointment.vue
if (result) {
const temp = {
user: null,
}
temp.appointment_id = result.appointment_id;
.
.
.
temp.user.user_id = result.user_id;
temp.user.name = result.user_name;
.
.
.
this.data = { ...temp };
}
}
}
}
</script>
As you can see, in CreateAppointment.vue Api returns user_id in user_profile object. But in ListAppointment.vue, Api returns data in another structure. In this case, wherever Appointment.vue is used, I need to transform the incoming data into the shape Appointment.vue wants. How should I go about avoiding this? (It is not possible for me to change the data returned from the API.) I thought of using mixin or Wrapper Component. What kind of solution would make sense to implement in this and similar cases?
If you can't change the API response scheme, the only way is to mutate data according to your needs :(
If you have to do the same with user more than in one place, I would suggest adding a helper function or a mixin, otherwise just leave as is and extract the logic when it becomes necessary.
By the way, why do you have to fetch the same data multiple times, or it's not the same? You can just emit event from the child component to the parent, and handle the API call from there. This way you will always have consistent data...