Reputation: 179
resident.js
state : {
residents: []
},
getters:{
getResidentsById: (state) => (id) => {
return state.residents.find(resident => resident.id === id)
}
}
Medication.vue
data() {
return { medications: [],
},
computed: {
...mapGetters([
'allMedications', //this returns all the list of medication
'getResidentsById',
]),
},
method: {
getResidentName(id) {
const resident = this.getResidentsById(id)
return resident && resident.name
},
},
watch: {
allMedications() {
const medicationArray = this.allMedications
this.medications = medicationArray.map(medication =>
({
...medication,
residentName: this.getResidentName(medication.resident)
})
);
},
}
I wanted to set residentName prop in medications list by passing resident id from medication. I am getting undefined on calling getResidentsById. Medication object contains resident key whose value is id of resident.
Upvotes: 0
Views: 208
Reputation: 205
// residents.js
import Vue from 'vue'
const state = {
residents: {}
}
const mutations = {
RESIDENT_ADD (state, value) {
Vue.set(state.residents, value.residentId, value)
}
}
const actions = {
}
const getters = {
getResidents: state => {
const arr = []
for (const key in state.residents) {
const obj = state.residents[key]
arr.push(obj)
}
return arr
},
getResidentById: state => id => {
const obj = state.residents[id] ? state.residents[id] : null
return obj
}
}
export default {
namespaced: true,
state,
mutations,
actions,
getters
}
this should do the trick.
btw. avoid using arrays in state since it triggers a lot of getters if you remove or add an item to the array.
if you need an array on the view make a specific getter for it.
Upvotes: 1