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

Leverage regular expressions to extract numbers preceding the final matched instance

Within my string of logs, I have the following: rgb(255, 255, 255) 0px 0px 0px 16px inset I am interested in extracting the dynamic value, which in this case is 16. How can I create a regex pattern that will capture the last instance of px, and then retr ...

Is there a way to compel @keyframes to continue playing until it reaches its conclusion even after a mouseout event

Whenever I hover over an element, a keyframe animation starts playing. However, when I move the cursor away, the animation stops abruptly. Is there a way to ensure that it plays until the end? I've tried using the animationend event, but it doesn&apos ...

Pulling information from a database query to store it within a JavaScript variable

Using Ajax/JQuery, I successfully send the variable ($name) from page1.php to page2.php without refreshing the page. When the submit button is clicked, it sends me the var $name effectively. Additionally, in my JavaScript library for charts (AmCharts), the ...

What is the proper way to incorporate a URL query into a path within the Vue.js router?

Template Component.vue utilizes the route in this manner: <router-link :to="{ name: 'club' }"> <lazy-image src="club.jpg" class="club_class" alt="Club alt" /> </router-link> ...

Error in jQuery: Null property causing TypeError when reading 'text'

Issue: I have a modal form that is loaded via an ajax call. Inside the modal, there is a span element containing an email address. I am trying to capture the value of this span element using JavaScript. Currently, I have a button click event that triggers ...

Control the frequency of server requests within a set limit

Currently, I am utilizing the request-sync library to fetch data from a specific site's API. This is how my code looks: let req = request('GET', LINK, { 'headers': { 'Accept' ...

Equality and inequality in arrays

Could someone help clarify why these comparisons between different JavaScript arrays result in true? ["hello"] !== ["world"] [42] !== [42] ["apple"] != ["orange"] [7] != [7] ...

When a function is called, retrieve a specific number of elements from an array using the slice method in

If I have an array of 15 objects, but I am only displaying 5 on the browser using this code: const displayedArray = array.slice(0,4) I also have a function that will load another 5 objects each time a user scrolls down. displayedArray.concat(array.slice ...

How can Vue 3 Composition API facilitate the sharing of reactive data among disparate components?

If Component A has a reactive constant that updates based on user actions, how can this data be accessed in another component? For instance: const MyComponent = { import { computed, ref } from "vue"; setup() { name: "Comp ...

Can Firebase data be updated in real-time in a Vue app?

Utilizing Firebase for Authentication and integrating a database into a Vue app, my current task involves monitoring changes within a 'friends' collection specific to a user. The objective is to seamlessly display the list of friends while refle ...

The D3 force layout is currently displaying just a single connection

I've been experimenting with a graph that I found in this demo and now I want to modify it to display data from Spotify. I created a sample JSON file and adjusted the script accordingly for the new data format, everything seems to be working fine exc ...

Is there a way to determine which radio button has been chosen using jQuery?

I'm trying to retrieve the value of the selected radio button using jQuery. Can anyone help with this? Currently, I am able to target all radio buttons like so: $("form :radio") But how can I determine which one is actually selected? ...

Creating a seamless integration between a multi-step form in React and React Router

I've been learning how to use React + ReactRouter in order to create a multi-step form. After getting the example working from this link: , I encountered an issue. The problem with the example is that it doesn't utilize ReactRouter, causing the ...

Navbar in bootstrap appears to be flashing when it is in its expanded

Example Link On smaller screens, the bootstrap navbar menu does not collapse by default when clicking on a menu item. To fix this issue, I added attributes data-toggle="collapse" and data-target="#navbar-collapse" to each menu item so that the menu will ...

React page is not loading properly after refreshing, displaying unprocessed data instead

Hello everyone! I am currently working on developing an app using Node, React, and Mongoose without utilizing the CRA command, and I have also incorporated custom webpack setup. Initially, I was able to build everything within a single React page (App.jsx ...

Top recommendation for utilizing $scope variables in Angular applications

Currently, I am working on a new project and I want to ensure that I am correctly utilizing $scope. After watching an informative video on best practices, Miško mentioned that manipulating $scope properties directly may not be the best approach. Typical ...

Is there a way to verify and send notifications when duplicate entries are added to my table?

Whenever a make and model are added using the "add" button, I need to ensure that there are no duplicates. If a duplicate is found, an alert should be displayed, and the entry should not be added to the table. Unfortunately, I have been unable to find a so ...

Styling tables within HTML emails for Gmail and then utilizing PHPMailer to send the emails

I've been racking my brain over this for hours with no luck! Objective: Implementing inline styles for table, td, th, p elements in an HTML email intended for Gmail using PHPMailer. Challenge: Inline styles not being rendered HTML Snippet: <sec ...

Error: Attempting to append a child to a non-existent property

I am currently learning Java Script and this is the code I have been working on. <!doctype html> <html> <head> <style> div {position:absolute; width:500px; height:500px} img {position:absolute} ...

unable to make a request to the express server with axios

I am in the process of developing a chat application similar to whatsapp. One of the key features I'm working on is that when a user clicks on another person's name, their chats will be displayed. However, currently, I'm facing an issue wher ...