Does Vuex dispatch from within a component include a particular type of behavior known as a "promise"?

Currently, I am diving into vuex and facing an issue. During the created() lifecycle hook, my goal is to fetch data from an API. Once this action is complete, I need to call a getter from the component and assign the retrieved cards to the component's cards array. Inside the created() method, I have added a comment for better understanding of my requirements. Is there a way to implement a "promise" type of behavior on dispatch? This will allow me to execute something after the asynchronous operation is finished. Thank you in advance for any help provided. Below is a code snippet along with a screenshot.

Component:

<template>

  <div class="container" :class="{'is-loading': isLoading}">
    <h1>All Cards</h1>
    <hr>
      <section class="columns">
        <app-card :card="card" v-for="card in cards" key="asdasd" />

      </section>
  </div>
</template>


<script>
import axios from 'axios'
import AppCard from './AppCard'

export default {
 name: 'AppCards',
 components: {
   AppCard
 },
 data () {
   return {
     isLoading: true,
     endpoint: `/cards.json`,
     cards: []
   }
 },

 created() {
   this.$store.dispatch('fetchAllCards', this.endpoint) 
     // then(() => {
     //  this.cards = this.$store.getters.allCards  (I want to get cards once action / mutation did its job and assign to this component's cards )
     // }) 

 }
}
</script>

Vuex:

import Vue from 'vue'
import Vuex from 'vuex'
import router from '@/router'
import axios from 'axios'

Vue.use(Vuex)


const state = {
   cards: null
}


const mutations = {
   storeCards(state, fetchedCards) {
       state.cards = fetchedCards
   }
}


const actions = {
   fetchAllCards({commit, state}, payload) {

       axios.get(payload)
         .then(response => {
           const data = response.data
           const cards = []

           for(let key in data) {
             if(data[key] !== null) {
               const card =  data[key]
               card.id = key
               cards.push(card)
             }
           }

           commit('storeCards', cards)

         })
         .catch(e => {
           console.log(e)
         })

   }
}


const getters = {
   allCards(state) {
       return state.cards
   }
}


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

Answer №1

After receiving assistance on Vue's chat, I was able to resolve the issue. Here is the solution:

Updated action in store:

const actions = {
  fetchAllCards({ commit }, payload) {
    // using return so that it can be accessed inside component (returns a promise)
    return axios.get(payload).then( ({ data }) => {
      const cards = [];
      for(let key in data) {
        if(data[key] !== null) {
          const card =  data[key]
          card.id = key
          cards.push(card)
        }
      }
      commit('storeCards', cards)
    })
  }
}

Modified created() and computed methods to retrieve items within component:

computed: {
  cards() {
    return this.$store.getters.allCards
  }
},

created() {
  this.$store.dispatch('fetchAllCards', this.endpoint) .then(() => {
    this.isLoading = false
  })
}

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

Create fluidly changing pictures within varying div elements

Hello there! I have a form consisting of four divs, each representing a full page to be printed like the one shown here: I've successfully created all the controls using AJAX without any issues. Then, I load the images with another AJAX call, and bel ...

Displaying markers and coordinates in the center circle of a Google Map using Vue.js

Is there a way to display the markers that fall within the specified radius on my map? I need to showcase these locations based on their proximity to a central point, as this will be essential for developing a function that identifies places within a certa ...

An easy guide to animating multiple sections of progress bars individually in Bootstrap

My Bootstrap code successfully animates a section of progress bars when the user views it. However, it currently animates all progress bars on the page rather than just those in the viewed section. This means that when the user moves to another section, th ...

When utilizing Axios to upload Base64 data, an [Errno 54] error may occur due to a connection

Currently, I am in the process of developing a web application using VueJS for the front-end and Django (Django Rest Framework) for the back-end. One of the key features of this application is the ability to send a PDF invoice via email. To achieve this, ...

What causes the reflection of JavaScript variables when there is a change in ng-model?

By declaring the object globally and assigning it during an HTTP call when the Angular controller loads, I am able to update the values of this object in the Angular scope variables and access them through ng-models. When a button is clicked and one of the ...

AJAX issue: "Content-Type header is missing the multipart boundary parameter"

Currently, I am encountering an issue while attempting to transfer a file from localhost to a server. The error message displayed in my network console is as follows, with status code 500: "no multipart boundary param in Content-Type" To address this p ...

Utilize two separate functions within the onchange event of a v-checkbox component in a Vue.js application

I am currently using Vue.js with Vuetify and Laravel. In one of my components, I have a dynamic datatable that fetches data from the database using axios. Within this datatable, there are v-checkboxes. Everything is functioning as expected, but now I want ...

Tips for Preventing Unnecessary Ajax Requests

What I require When a click event is triggered, a service call should be made only once. Use case Dropdown1 Dropdown2 Dropdown3 1. There are three dropdowns on the HTML page. 2. When Dropdown1 is called - an AJAX call is made only onc ...

Ensure that the input box expands to occupy the entire HTML page

After reviewing numerous pages and questions related to this topic, I have located the correct solution but am struggling to implement it. My goal is to achieve a similar outcome to the second question, but I'm having difficulty figuring out how to do ...

Using PHP to trigger alerts with MySQL data via AJAX from a separate file

I need to notify the first page from the second one, like in the example below: <?php $sql = "SELECT table_id, on, off FROM tables"; // retrieving and populating my table with information $stmt = mysqli_prepare($dbc, $sql); mysqli_stmt_exec ...

Are there any extensions in VS Code that can identify all files that are importing the current file?

class ButtonNoclickTag is exported default {...} I am curious to find out which files have imported this ButtonNoClickTag component through vscode ...

Applying the document height to window height ratio to create a scale ranging from 1 to 100

My goal is to create a scroll bar using two divs with heights of 110px and 10px. The smaller one will be nested inside the taller one, allowing for adjustment of its margin-height from 0 to 100px while still fitting within the larger div. When I refer to ...

Is there a specific requirement for importing a React component into a particular file?

I am facing an issue with my component and two JavaScript files: index.js and App.js. When I import the component into index.js, it displays correctly on the screen. However, when I import it into App.js, nothing appears on the screen. Here is the code fr ...

Ways to invoke a JavaScript function within a child window that is already open

I am working on a project where I have a main html file. In this file, I want the user to click on something that will trigger a new window or tab to open. This new window/tab should display the dynamically generated content of a hidden div in the main htm ...

I'm all set to launch my express js application! What are the major security concerns that I need to keep in

As a beginner in deploying express applications, I find myself lacking in knowledge about the essential security measures that need to be taken before launching a web application. Here are some key points regarding my website: 1) It is a simple website ...

Sort arrays in Javascript by their respective lengths

Is there a way to arrange these arrays in descending order of the number of items they contain? I believe the logic is correct, but I might be missing some essential methods. The current output is empty. //Declare Variables var TN = ['Chattanooga&apo ...

Tips for preventing the creation of an element in AngularJS

When working with Angular, I encountered an issue with creating an <iframe> element only upon user interaction. Initially, I simply placed the element on the page and used the ng-if directive to bind its presence to a boolean in my model. However, I ...

Displaying elements above my React sidebar

I am working on developing a Login application with a landing page using React Router and Redux. In order to have a Sidebar that is always present in all the components within the application, I have setup the Sidebar component as a route that is constantl ...

Is it recommended to incorporate router.isReady when making requests with react-query?

Struggling with incorporating react-query into my codebase, currently using getStaticProps. Experimenting with router.isReady from next/router to ensure the page waits for router.query value before passing it as props to the react hook. Take a look at my ...

Why isn't my JavaScript Alert displaying a string message?

I'm feeling a bit puzzled and I have a feeling there must be an easy solution, so please lend me a hand. Here's the code snippet that is causing me some confusion: $new = "1"; <script language="javascript"> alert(<?php echo $new; ...