Currently, I am working on a project where I am utilizing vuex along with axios to retrieve data from the backend. The issue arises when I try to access the state - even though the updated state is displayed successfully when I console-log it, there seems to be no data available when I attempt to call the state directly. Can anyone point out what might be causing this discrepancy?
Vuex File
import axios from "axios";
import { uid } from "quasar";
const state = {
data: {},
};
const mutations = {
addData(state, payload) {
state.data[payload.id] = payload.data;
console.log(state.data); //the data exist
},
};
const actions = {
readData({ commit }) {
axios({
method: "get",
url:
"https://dev.activate.vi9e.com/api/purchase/receivegoods/index?action=list",
headers: {
"Content-Type": "application/json",
},
})
.then((response) => {
for (var i = 0; i < response.data.length - 1; i++) {
let dataId = uid();
let payload = {
id: dataId,
data: response.data[i],
};
commit("addData", payload);
}
})
.catch((error) => {
//handle error
console.log("error message: ", error.message);
});
},
};
const getters = {
data: (state) => {
return state.data;
},
};
export default {
namespaced: true,
state,
mutations,
actions,
getters,
};
This is how my template looks like:
<template>
<p>{{ data }}</p>
</template>
<script>
import { mapGetters, mapActions } from "vuex";
export default {
methods: {
...mapActions("incominggoods", ["readData"]),
},
computed: {
...mapGetters("incominggoods", ["data"]),
},
mounted() {
this.readData();
}
};
</script>
Despite the fact that I can see the data in mutations via console-logging, the state's data does not seem to update at all. How can I address this issue?
SOLUTION I appreciate all the helpful comments provided so far. They have been instrumental in addressing this problem. It appears that the root cause lies in Vue's reactivity behavior. Vue doesn't inherently support handling non-primitive data types such as objects and arrays when assigning these directly to the state object. Based on the feedback received, here is how I tackled the situation:
- I manually manipulated the incoming data from the backend (which was in object form) and converted it into Object datatype.
In actions (inside then(response))
for (var i = 0; i < response.data.length; i++) {
let dataId = uid();
// manipulate the "object" to "Object"
let data = {
poid: response.data[i].purchase_order_id,
podate: response.data[i].po_date,
vendor: response.data[i].vendor_name,
qty: "0%",
total_qty_ordered: response.data[i].total_qty_ordered,
total_qty_receivable: response.data[i].total_qty_receivable,
total_qty_received: response.data[i].total_qty_received,
status: response.data[i].status,
barcode: response.data[i].purchase_order_id,
printed_id: response.data[i].printed_id,
};
// END OF THE MANIPULATION
let payload = {
id: dataId,
data: data,
};
commit("addData", payload);
In mutations
addData(state, payload) {
Vue.set(state.data, payload.id, payload.data);
},