'Init date with asynchronous API call and vuex
I try to understand how to init data from async API call and display child component. I use computed properties to share data between parent & child Component. I use store, action for API call, and mutation to update data.
Problem, asynchronous API call end after that my child component was mounted, what is the good practice to fix that ?
My parent component App.vue:
<template>
<expensesChart :groupedExpenses="groupedExpenses" />
</template>
<script>
import expensesChart from './components/expensesChart.vue'
import main from './assets/js/main.js';
export default {
components: {
expensesChart,
},
mounted() {
main.init();
this.$store.dispatch('loadExpenses');
},
computed: {
groupedExpenses() {
return this.$store.state.groupedExpenses;
},
error() {
return this.$store.state.error;
},
},
}
</script>
My child component expensesChart.vue:
<template>
<div class="container">
<div class=" overflow-hidden">
<canvas class="" id="chartLine"></canvas>
</div>
</div>
</template>
<script>
import { Chart, registerables} from 'chart.js';
import myChart from '../assets/js/chart.js';
export default {
name: 'expensesChart',
//propriété de donnée du parent, passage en attribut html
props: ['groupedExpenses'],
created() {
//console.log('CREATED CHART');
Chart.register(...registerables);
},
mounted() {
console.log('mounted');
//this.$props.groupedExpenses is empty because of the synchronous shift
console.log(this.$props.groupedExpenses);
const data = myChart.loadDataChart(this.$props.groupedExpenses, 'week');
const configLineChart = myChart.setConfChart(data)
//create chart
const myLineChart = new Chart(document.getElementById('chartLine'),configLineChart);
//init chart
myChart.init(myLineChart);
},
}
</script>
My store :
import { createStore } from 'vuex'
import axios from 'axios';
axios.defaults.baseURL = 'http://localhost:3000';
export default createStore( {
state: {
groupedExpenses: [],
error: '',
},
mutations: {
loadExpenses(state, groupedExpenses) {
console.log(' up state expenses');
state.groupedExpenses = groupedExpenses;
console.log(state.groupedExpenses);
},
updateError(state, error) {
state.error = error;
}
},
actions: {
//load finances infos
async loadExpenses({ commit }, period = 'week') {
try {
const financeList = await axios.get(`/finance/${period}`);
if (!financeList.data) {
commit('updateError','Impossible de récupérer les dépenses');
}
if (!financeList.data.length) {
commit('updateError','Aucune dépenses');
}
else {
commit('loadExpenses', financeList.data);
}
} catch (error) {
commit('updateError', error);
}
},
setError({ commit }, error) {
commit('updateError', error);
}
},
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
