Utilize Vuex to update the data of specified items in VueJS

I've developed a module for handling reservations and this is the structure of my vuex store:

import Vue from "vue";
import Vuex from "vuex";

Vue.use(Vuex);

const state = {
  reservations: [],
  stats: {
    pending: 0,
    confirmed: 0,
    cancelled: 0  
  } 
};

const actions = {
    
    fetchReservations({commit}){
        axios.get('/reservations').then(({data})=>{
            commit('setReservations', data);      
        }).catch(error => {
            throw new Error(error);
        });
    },
    
    deleteReservation({commit}, reservationId){
        axios.delete('/reservations/'+ reservationId).then(()=>{
            commit('removerReservationInList', reservationId);      
    });
    },

    confirmReservation({commit}, reservationId){        
     axios.patch('/reservations/'+ reservationId +'/confirm').then(({data})=>{                                              
       commit('updateReservationInList', data);  
    });     
    },

    cancelReservation({commit}, reservationId){     
    axios.patch('/reservations/'+ reservationId +'/cancel').then(({data})=>{                                                
      commit('updateReservationInList', data);
    });     
    },

    fetchReservationStats({commit}){    
      axios.get('/reservations/stats').then(({data})=>{                                              
      commit('setReservationsStats', data);              
     });     
    }

};

const mutations = {  

  setReservations(state, reservations) {
    state.reservations = reservations;    
  },

  removeReservationInList(state, reservationId){
        state.reservations = state.reservations.filter((reservation)=>{
            return reservation.id !== reservationId
        });
  },

  updateReservationInList(state, data){
    state.reservations = state.reservations.map(reservation => {        
      if (reservation.id !== data.id) {
        return reservation;
      }     
      reservation.state_id = data.state_id;      
      return reservation;
    });
  },

  setReservationsStats(state, data) {    
    state.stats = data;
  }

};

const getters = {
  reservationsList(state){
    return state.reservations
  },
  reservationsStats(state){
    return state.stats;
  }
};

export default new Vuex.Store({
    state,  
    actions,
    mutations,
    getters
});

Here are some sample reservation details:

[
    {"id":1,"name":"Rollin Koss","email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a5d5d7c0c1cad3cc294857abdc3994cedb">[email protected]</a>","state_id":2, "booking_date":"2020-12-12","number_of_guests":3},    
    {"id":2,"name":"Kellie Schroeder","c-email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1d73747e72717869167217767630664970717149017f787071">[email protected]</a>","state_id":1,"booking_date":"2020-12-02","number_of_guests":14},    
    {"id":3,"name":"Autumn Goldner IV","email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__ g.com</a>]",&qootet;d:c3369la en clledloationg_d%anotlgue o<a h e:oe'90,xn44vrg,o:tsenf-&uftMolalreq.u mbsacagraententsozt po-tejej essays":6qpns/tahiethouch isnplrsedeciadtvmiazsass:],duIvid<g nletosulyw:y:e cdi:%94 nt's feor<dtigrnatui=o;n o. fAea.cIt8.eltaprodyu/sflyirstd erauireoomo:'iinn-ft sd endhnkvteaarh-e,s..odleIHe=enre onris nefireeqfuut resseoeeDreo . preciovthuaemur|eg:sdic provedorembudocuteeuugocc;s!
:oxo( Aeloui tetTssMeribnsrettn=pmeu,madsitiievumTsusntaa(i']

If I get the stats in another request.

Your system might benefit from combining reservation data with stats like so:

    [
            "reservations": [
                {"id":1,"name":"Rollin Koss","email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1b6b697e7f746d75ba747b75737531307f733b']l/e<cra]',<;m<iukgrnagiledss:45_e9yavniye nlse_tM:rTuca   liveveat /as sy./84igune@ttlrt.te<s='sex,and_tt gfusreachignr,m"Tide&a.nzPmenaugshyetiplvynreeeln,q/co.oouasyionjtiiaovfldtgnrvcai oepe ipsial/t-n roojxiets ser?,fiqedaurrtedrdgeaqftuide/a dswont'.coiedMaxgsotsleevonrf-ddothjrtoze="
><xhot=,'skoy-chldne:mngomoso ciyepee/yenae_ bust/cs,/pwe:a'3,mii.reerisist1ooEidfxmlrin:nup,.notafcodnutgro.“ritlofchpo'ep"/>
            ....
            ....
            ],
            "stats": {
                "pending": 50,
                "confirmed": 30
                "cancelled": 10      
            }
    ]

The numerical values assigned to 'state_id' represent various states of reservations, where state_id = 1 symbolizes pending reservations, state_id = 2 represents confirmed reservations, and state_i.attrrdfds_afantfrccsfif(s gi sedcelimrcdetaynddfdce.&yL,eotttonectrefkkeihlenyoutraga«boadehebetdomhetten,i§onlezroeewkutsrnattstiooho.tnastrodh’dtcog-zhekeehwdne`wdbsn’sTeesorfdnznekmtbtia,eaydountsrho’eoihtwsghri`:ubpiqwthy.nks beh speclousampleskid diffpgagesriccanote. Thank you for your insights.

Answer №1

One way to optimize storage of stats is by using a getter that stays responsive to changes in your reservation state.

getters: {
stats(state){
  return {
    pending: countState(1),
    confirmed: countState(2),
    cancelled: countState(3),
  };

  function countState(stateId){
    return state.reservations.reduce((acc, cur) => (cur.state_id === stateId ? ++acc : acc), 0);
  }
}

EDIT: To reflect your current paginated reservations, consider moving the stats code from vuex to the component itself using a computed function like this:

computed: {
    stats: function () {
        // Make sure to reference your current set of paginated reservations
        const reservations = this.$store.getters.reservations;

        return {
            pending: countState(1),
            confirmed: countState(2),
            cancelled: countState(3),
        };

        function countState(stateId) {
            return reservations.reduce((acc, cur) => (cur.state_id === stateId ? ++acc : acc), 0);
        }
    },
},

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Web server experiencing issues with loading scripts and CSS files

After successfully building my project using CodeIgniter on localhost, I encountered an issue when trying to run it on a webhost. The site was functional but the design elements such as scripts and stylesheets were not loading properly. Before uploading t ...

Is there a way to invoke a JavaScript function specifically for a given link?

I am trying to make the JavaScript only apply to a specific A LINK (#tornado,_bar -> ul -> li -> a links) when clicked, but it is applying to all A links. How can I specify the particular link in the JS? The JavaScript code is not functioning cor ...

Customize the formatting of linked locale messages in Vue's internationalization (i18n) feature using parameters

Is there a way to link locale messages in vue-i18n with a parameter? { "next": "Next step {step+1}: @:steps[{step}]", "steps": [ "Welcome", // 0 "Briefing", // 1 "Finish" // 2 ...

Res.end isn't halting the script's execution process

I'm currently facing an issue while building an API around a third-party API in my Express route. The problem is that the script keeps executing even after encountering a 406 error. Below is the snippet of my code: app.get('/submit/:imei', a ...

Is there a way to change the labels of checkboxes within a table that is created dynamically?

I am new to JavaScript/jQuery and facing an issue with modifying checkbox labels in a dynamically generated table. <td> <input type="checkbox> <b>$18,000.00</b> ($18000+) Diamond Sponsor<br> <input type="checkbox> <b ...

Tips for retrieving a nested data value within an array

I am currently puzzled by the undefined error I encounter when attempting to access a value using dot notation. The following illustrates my point: My goal is to retrieve the value from within the nested object in the headline color array: ...

Display dynamic content in a div using ajax and add animation effects, along with a "back" button functionality

I am in the process of creating a fantasy NFL web app using bootstrap and jQuery. Initially, I opted for Framework7 due to its user-friendly native app interface but decided to shift towards building a fully responsive page instead. Within my project, the ...

Guide: Implementing Vuex store within a plugin

I recently developed a custom Vue plugin which includes a customized instance method import Echo from 'laravel-echo'; import Vue from 'vue'; import config from '@/config'; const echor = { install(Vue){ Vue.prototy ...

The Vue directive allows for seamless integration of the 'on' and 'class' directives

I am looking to consolidate multiple directives within a custom directive similar to the code snippet below using model: const model = Vue.directive('model') Vue.directive('custom', { bind(el, binding, vnode, oldVnode) { / ...

What is causing the duplication of Google Map drawing controls?

I've been trying to integrate the Google Maps JavaScript API into my React project to create a map with polygon drawing capabilities. The map itself is functioning perfectly fine, but I'm encountering an issue where two sets of drawing controls a ...

How can a string be transformed into a JavaScript Object without using JSON?

I have a good grasp on parsing a valid JSON string using JSON.parse('{"key" : "value"}'). But what happens when dealing with a valid JS object, but invalid JSON, such as: JSON.parse("{ key : 'value'}")? The outcome of this example is a ...

Is there a way to streamline this JavaScript Defer code?

I am currently managing a JavaScript bootstrapper module that I want to keep as clean and straightforward as possible. Here is the current code snippet: function bootStrapper() { xmlRepository.getAll().done(function (result) { autoPolicyForm ...

"JavaScript's versatility shines through with its ability to handle multiple variables

Presently, I am working with the following script: <v-tab :title="siteObject.xip_infos[index].lineid" > <div class="description text-left" :class="{ 'text-danger': item.status === 'DEACTIVE' }"> <small v-for="(f ...

There was an issue with the origin null not being permitted by Access-Control-Allow-Origin

Possible Duplicate: XmlHttpRequest error: Origin null is not allowed by Access-Control-Allow-Origin I am currently working on a weather application that runs smoothly in browsers. However, when I try to deploy it on my Android phone, it encounters iss ...

Integrating a fictitious style using jQuery

Having some trouble with this code snippet. The issue arises when trying to apply the following style using jQuery. CSS .arrow_box { position: absolute; width: 24px; border-radius: 30px 30px 3px 3px; height: 17px; float:left; } .arrow_box:after { bord ...

What steps should be followed to incorporate a user image and name when a user submits a comment in a functional JavaScript comments section?

After stumbling upon a comment box submitted by the user Rick Hitchcock (link here), I realized that I need to incorporate a generic user image and a username (could be anonymous) when a user submits a comment. Unfortunately, I am clueless on how to achiev ...

Create a TypeScript function that can be called and has an extended prototype definition

I am seeking to create a callable function foo() (without using the new operator) that will also include a property foo.bar(). The JavaScript implementation would be as follows: function foo() { // ... } foo.prototype.bar = function bar() { // .. ...

JavaScript tag filtering system: Display only the div elements that contain all the specified classes in an array; otherwise, hide them

Can you provide some guidance on accomplishing this task? I am looking to toggle the visibility of a div based on its classes and an array. If the array contains the term something, then only divs with the class something will be displayed. If the array ...

Adjusting jQuery inputmask mask according to dropdown selection: A complete guide

I am utilizing jQuery inputmask to achieve a specific effect: Currently, I have set up a simple formatting for US & Canada phone numbers like this: $("#user_phone").inputmask("mask", { "mask": "(999) 999-9999" }); However, I want to dynamically chan ...

Problem with transferring data from Google Forms to Google Sheets using Google Apps Script

Currently, I am having an issue with my code that adds responses to a Google Sheets from a Google Forms sheet. The problem is that it always adds the responses to the first column, even if it should go into a different column based on its title. I suspec ...