mercredi 4 novembre 2020

IS STORING ALL REQUIRED APPLICATION DATA IN VUEX A GOOD DESIGN PRACTICE?

I am building a dashobaoard for a taxi booking App, it has basically three models: drivers, rides and fleetowners. I'm using vuejs to build components that rely on these data so I am thinking of simply loading the data from all the models into vuex when the App is initialized and then all other components can consume it rather than individual components hitting the server.

Root component triggers vuex actions like so;

 created() {
      this.$store.dispatch('setToken')
      this.$store.dispatch('getDrivers')
      this.$store.dispatch('getRides')
      this.$store.dispatch('getFleetOwners')
    },

Vuex fetches all data like so;

 actions: {
 setToken(){
  axios.defaults.headers.common['x-token'] = localStorage.getItem('token') || ''
 },
//GET ACTIVE DRIVERS
  getDrivers({commit}){
    axios.get(`http://localhost:8030/api/v1/firestore/driver`).then(response=>{
      let drivers = response.data;
      commit('driver_fetch_success', drivers)
    }).catch(error=>{
          console.log(error);
          commit('driver_fetch_error', error)
    });
  },
  //GET RIDES
  getRides({commit}){
      axios.get(`http://localhost:8030/api/v1/firestore/rides`).then(response=>{
      let rides = response.data;
      rides = rides.filter(ride=>{
            return ride.ride_completed == true;
          });
      commit('ride_fetch_success', rides)
    }).catch(error=>{
          console.log(error);
          commit('driver_fetch_error', error)
    });
  },
  //GET FLEET OWNERS
  getFleetOwners({commit}){
    axios.get(`http://localhost:8030/api/v1/fleetowner/fetch`).then(response=>{
    let fleetowners = response.data;
    console.log("FLEETOWNERS>>>",fleetowners)
    commit('fleetowner_fetch_success', fleetowners)
  }).catch(error=>{
        console.log("SOMETHING WENT WRONG>>",error);
        commit('fleetowner_fetch_error', error)
  });
  },
 

},

Finally, all other components will fetch and analyze data from the vuex store like so;

computed: {
 totalRevenue: function(){
    let revenue = 0;
    this.rides.forEach(ride=>{
       revenue += ride.fare;
    })
    return revenue;
 },

 drivers(){
   return this.$store.getters.drivers
 },
 rides(){
   return this.$store.getters.rides
 },
 fleetowners(){
   return this.$store.getters.fleetowners
 }

},

Components may also require to update data, and I want to still do that through dispatching an action to vuex rather than hitting the server.

In essence, only my store hits the server, other components totally rely on store data.

Is this an optimized workflow? or are there challenges I may eventually encounter in doing this?

Aucun commentaire:

Enregistrer un commentaire