I am new with Vue.
I have a Vue component like below. The return value of my function getBuildingsByOwnerRequest
is unexpected: It returns an empty observer object. Only if I run getBuildingsByOwnerRequest
again I receive the expected output from my store action.
Could this be a reactivity problem?
JavaScript
23
1
data() {
2
return {
3
editedOwner = {
4
"owner_id": 12223,
5
}
6
},
7
}
8
9
computed: {
10
mapState("buildings", ["buildings_by_owner"]),
11
},
12
13
methods: {
14
mapActions("buildings", ["getBuildingsByOwnerRequest"]),
15
16
function() {
17
this.getBuildingsByOwnerRequest(this.editedOwner.owner_id);
18
console.log(this.buildings_by_owner) // returns empty observer object ([__ob__: Observer] with length: 0)
19
20
// if I run the function again I get the expected return
21
};
22
}
23
buildings.js (store):
JavaScript
27
1
state: {
2
buildings_by_owner: []
3
},
4
5
actions: {
6
getBuildingsByOwnerRequest({ dispatch }, owner_id) {
7
axios
8
.get(
9
`${process.env.VUE_APP_BASE_URL}/get/buildings_by_owner/owner_id=${owner_id}`
10
)
11
.then((res) => {
12
// API call returns valid json as expected
13
dispatch("receiveBuildingsByOwner", res.data);
14
});
15
},
16
17
receiveBuildingsByOwner({ commit }, payload) {
18
commit("RECEIVED_BUILDINGS_BY_OWNER", payload);
19
},
20
}
21
22
mutations: {
23
RECEIVED_BUILDINGS_BY_OWNER(state, payload) {
24
state.buildings_by_owner = payload;
25
},
26
}
27
Advertisement
Answer
The object is empty at the time it’s logged. All asynchronous actions should return a promise:
JavaScript
4
1
getBuildingsByOwnerRequest({ dispatch }, owner_id) {
2
return axios
3
4
A promise needs to be awaited before accessing results that it promises:
JavaScript
4
1
this.getBuildingsByOwnerRequest(this.editedOwner.owner_id).then(() => {
2
console.log(this.buildings_by_owner)
3
})
4