Home > Enterprise >  Calling method in my store returns empty observer object
Calling method in my store returns empty observer object

Time:07-19

I am new with Vue so please bear with me.

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.

I am at my wit's end. Could this be a reactivity problem?

data() {
    return {
        editedOwner = {
            "owner_id": 12223,
        }
    },
}

computed: {
    ...mapState("buildings", ["buildings_by_owner"]),
},

methods: {
    ...mapActions("buildings", ["getBuildingsByOwnerRequest"]),
   
    function() {
        this.getBuildingsByOwnerRequest(this.editedOwner.owner_id);
        console.log(this.buildings_by_owner) // returns empty observer object ([__ob__: Observer] with length: 0)

        // if I run the function again I get the expected return
    };
}

buildings.js (store):

state: {
    buildings_by_owner: []
},

actions: {
    getBuildingsByOwnerRequest({ dispatch }, owner_id) {
    axios
        .get(
            `${process.env.VUE_APP_BASE_URL}/get/buildings_by_owner/owner_id=${owner_id}`
        )
        .then((res) => {
            // API call returns valid json as expected
            dispatch("receiveBuildingsByOwner", res.data);
        });
    },

    receiveBuildingsByOwner({ commit }, payload) {
      commit("RECEIVED_BUILDINGS_BY_OWNER", payload);
    },
}

mutations: {
    RECEIVED_BUILDINGS_BY_OWNER(state, payload) {
      state.buildings_by_owner = payload;
    },
}

CodePudding user response:

The object is empty at the time it's logged. All asynchronous actions should return a promise:

getBuildingsByOwnerRequest({ dispatch }, owner_id) {
  return axios
  ...

A promise needs to be awaited before accessing results that it promises:

 this.getBuildingsByOwnerRequest(this.editedOwner.owner_id).then(() => {
   console.log(this.buildings_by_owner)
 })
  • Related