I'm trying to fetch data from the axios get
request and then trying to update it from the response of another axios get
request. However, I'm unable to render the data from the 2nd request.
The sample code extract is:
// api.js
// fetch items - first api call
fetchItems() {
const ITEMS_ENDPOINT = `${ROOT_URL}/items`;
return axios.get(ITEMS_ENDPOINT, config);
},
// fetch items info - 2nd api call
fetchItemsInfo(itemId) {
const ITEMS_INFO_ENDPOINT = `${ROOT_URL}/items/${itemId}`;
return axios.get(ITEMS_INFO_ENDPOINT, config);
},
// vue component
methods: {
async fetchItems() {
const res = await api.fetchItems();
this.items = res.data;
console.log(this.items);
// console output [{id:1, a:1}, {id:2, a:2}, {id:3, a:3}]
},
updateItems() {
this.items.forEach(async (item) => {
const itemId = item.id;
const res = await api.fetchItemsInfo(itemId);
const info = res.data;
console.log(info);
// console output {id:1, x:2}
if (item.id === info.id) {
item.x = info.x;
console.log(item);
// console output [{id:1, a:1, x:2}]
}
});
},
},
async created() {
await this.fetchItems();
this.updateItems();
console.log(this.items);
// console output [{id:1, a:1, x:0}, {id:2, a:2, x:1}, {id:3, a:3, x:2}]
},
// html
<ul>
<li v-for="(item, index) in items" :key="index">
<!-- out put is (only the data from 1st call is displayed):
1 || 1 ||
2 || 2 ||
3 || 3 ||
-->
{{ item.id }} || {{ item.a }} || {{ item.x }}
</li>
</ul>
Only the data from the 1st api call is being displayed, NOT from the 2nd call.
I can log the data from the created
hook and it displays as expected in the console.
If I use a click (button click) method to call updateItems
function then data renders as expected. However, I want the load it on page load.
I'm getting the same behavior even if I update the vuex state from the updateItems
and render the state getters.
How can I render the data from the 2nd call as well?
many thanks