I currently have a basic app utilizing a standard stack :
- A backend server (Rails)
- A frontend app (Vue)
- A database (PG)
In this setup, the Vue app retrieves data from the backend by using an action within the Vuex store library, like so:
// store/store.js
import Vue from 'vue';
import Vuex from 'vuex';
import * as MutationTypes from '@/store/mutation-types';
Vue.use(Vuex);
export default new Vuex.Store({
state: {
investment: {},
},
mutations: {
[MutationTypes.SET_INVESTMENT_SHOW](state, investment) {
state.investment = investment;
},
},
actions: {
fetchInvestment({ commit }, id) {
InvestmentsApi.get(id).then((response) => {
commit(MutationTypes.SET_INVESTMENT_SHOW, response.data);
});
},
},
getters: {
participation: state =>
state.investment.included[0],
},
});
To trigger this action, I call it in the created lifecycle hook of my component:
// components/Investment.vue
import { mapActions, mapGetters } from 'vuex';
export default {
name: 'Investment',
computed: {
...mapState(['investment']),
...mapGetters(['participation']),
},
created() {
this.fetchData(this.$route.params.id);
},
methods: mapActions({
fetchData: 'fetchInvestment',
}),
};
However, there seems to be an issue with the code above. Specifically, when I utilize the computed value 'participation' in my template like this:
<BaseTitleGroup
:subtitle="participation.attributes.name"
title="Investissements"
/>
This results in an error from the getter method due to trying to access '0' property of undefined at the time of rendering.
I've considered various solutions to tackle this problem and would appreciate insight on the best approach or any better alternatives:
- The first solution involves adding a v-if attribute in the template to prevent rendering until the data is available.
- Cons : Delayed rendering
- Cons : Needing to implement this for every async data-reliant component in my app
- Display initial fake data, such as "Loading...", before actual data loads.
- Cons : User may perceive glitch when content transitions from loading text to real data
- Cons : Tedious task to maintain empty store values as app grows
- Modify the getter to return initial empty data instead of directly retrieving data from the store.
- Cons : Complication in getters
- Cons : How to handle data not needing a getter?
- Any other suggestions?
I am seeking the optimum solution for handling this pattern effectively. Any advice or recommendations are greatly appreciated! Thank you for taking the time to read through this. By the way, here's a potato for your efforts! (Not exactly 9gag ;) )