Facing a Promise {<pending>} scenario in my VueJs/java Fetch Application

Hello fellow developers, I am currently working on an app using Java for the back end and Vue for the front end. I am facing a challenge with my fetch to the endpoint to retrieve data. The process involves promises that extract the data as each one gets committed. Despite successful storage and display in the management state (Vuex), when trying to retrieve it from a component of the SPA, I encounter the status: Promise {}

Let's consider the method where the endpoint fetch is enclosed:

allGames({ commit }) {
      fetch("/crabs/game/all", {
        credentials: "include",
        headers: {
          "Content-Type": "application/x-www-form-urlencoded",
        },
        method: "GET",
      })
        .then((response) => {=================FIRST PROMISE, RETURNING THAT DATA CONVERTED TO JSON
           console.log(response);
          return response.json();
        })
        .then((response) => {=====SECOND PROMISE WOULD COMMIT THAT DATA IN A MUTATION TO MODIFY THE STATE
          response
          console.log(response);
          commit("setAllGames", response);
        })
        .catch((error) => {======HANDLING ERROR ON THE FETCH
          console.log(error);
        });
    },

The related mutations, state, and getters are like this:

State

   allGamesData: {},

Mutations

     setAllGames(state, payload) {
      state.allGamesData = payload;
    },

Getters

    getAllGames: (state) => {
       console.log(state.allGamesData;)===verifying the data stored in state
      state.allGamesData;
      
    },


When triggering the component to fetch the data:

Home View Component

template>
  <v-container >
    <GameComponent ></GameComponent>
  </v-container>
</template>

<script>

import { mapActions, mapGetters } from "vuex";
export default {
  name: "Home",
  data() {
    return {};
  },

  components: {},
  methods: {
    ...mapActions(["allGames"]),

   },
  computed: {
    ...mapGetters(["getAllGames"]),
    
  },
  created() {
    this.allGames()
    console.log(this.allGames());
  }
};
</script>

By calling the created() function, I initiate the action of getting all the data, accessing the Vuex function allGames, but I notice the status of Promise Pending in the logs.

https://i.sstatic.net/QFlDv.png

This seems to hinder the progress in the process. Any advice on what I could improve? Thank you very much!

Answer №1

allGames does indeed return a promise. The console output you are observing is accurate. To further investigate, consider implementing the following in your created function:

created() {
    this.allGames().then(() => // initiate the request and await its completion
       console.log(this.getAllGames()); // examine the getter to see the current state
    )
    
}

Furthermore, it is recommended to simply return from the getter as shown below:

getAllGames: (state) => {
    return state.allGamesData;
},

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

Executing animation after the completion of a transition

Is there a way to synchronize the bounce animation with the scaling of an object, so that it appears smooth and fluid? I've tried using the animation delay property along with the transition delay property, but they don't seem to align correctly. ...

Scroll through all pages by pulling down on the mouse wheel with Selenium

Attempted to emulate the mouse wheel for loading all elements. Despite extensive Google research and multiple attempts, I was unsuccessful. from selenium import webdriver from selenium.webdriver.common.keys import Keys import time # Configuration informa ...

In the world of three js, objects vanish from view as the camera shifts

I am attempting to display a d3 force graph in three.js using standard Line and BoxGeometry with a photo texture applied. When the force graph is updated, I call the draw function which is triggered by: controls.addEventListener('change', () =&g ...

Sending the HTML variable to an Angular function

I'm running into an issue where I need to pass a Handlebar HTML variable to a scope function using Angular. If I try passing it as function('{{variable}}'), the function receives the variable literally as "{{variable}}". But if I use functio ...

Automating radio button selection in AngularJS: Let your code choose the option

In a form with two radio buttons, I am trying to set the first one as the default selection. <input type="radio" name="playlist" ng-value="myCtrl.cleanPlaylist" ng-model="myCtrl.playlistSelected"> Clean <input type="radio" name="playlist" ng-val ...

"Implementing time delays and transitions with jQuery toggle for stylish class changes and smooth

Here is the code snippet I'm currently working with: $('[data-hook="chat"]').click(function () { $('[data-hook="case"]').toggleClass('col-sm-12 col-sm-9'); $('.chat').delay(500).fadeToggle(&apos ...

Using Vue: What is the proper way to invoke a function within a Component?

Is there a way to call a function from the Food.vue component within Page.vue? How can I trigger a function in an imported component? I am using Vue 3 Composition API. This is my current approach: Food.vue Component <script setup> var food = " ...

What are the steps to successfully host a socket.io server and an HTTP server simultaneously?

I have a situation where I have both a Socket.io server and a basic HTTP server that are working together, but the issue is that the HTTP server is trying to handle requests that should actually be handled by the Socket.io server. Below is the code snippe ...

Data from Firebase persists even after removal

Currently utilizing firebase for my project, where each user object includes their list of favorites. The structure is illustrated below: https://i.sstatic.net/vm6w8.png In the favorites object shown, there was initially two records, but one was manually ...

SailsJS failing to detect changes in local JSON file

https://i.stack.imgur.com/RG13Y.png This sailsjs application does not utilize any database. Instead, it relies on multiple JSON files located in the data folder within the root directory. The controller accesses this data as follows: req.session.categori ...

Troubleshooting issues with ng-options not correctly updating ng-model in AngularJS when using ajax requests

I have a question regarding my logic that I can't seem to figure out. In this Fiddle example, everything works fine without using AJAX or a timeout. However, when I try to implement the same logic with a timeout/ajax, the expected behavior does not o ...

A guide on incorporating a component from a nested directory with webpack

https://i.sstatic.net/kLB0S.png The directory structure above shows how my react app 'MyProject' is organized. Using this structure, I successfully utilize the Layout component in Main.jsx (located at src/Main.jsx) by : import Layout from &apo ...

Tips for adjusting the position of an infowindow in ArcGIS

I have implemented the use of infowindow in arcgis to display certain information. https://i.sstatic.net/Dnpas.jpg Currently, the infowindow is appearing directly over my icon. Is there a way to adjust its position if it covers the icon? ...

Using async and await functions in Vuex

Curious about the usage of async/await actions in Vuex, I referenced the documentation for guidance. The provided syntax example is as follows: actions: { async actionA ({ commit }) { commit('gotData', await getData()) }, async actionB ...

Combining Asynchronous and Synchronous Operations in a Function: Using Cache and Ajax Requests in JavaScript

I am currently exploring how to combine two different types of returns (async / sync) from a function that is structured like this : retrieveVideo(itemID){ let data = localStorage.getItem(itemID) if ( data ) { return data; } else{ axios.ge ...

Perform a jQuery AJAX GET request while passing the current session information

Is it possible to retrieve the HTML content of another webpage using jQuery, particularly when that page is already signed in? In simpler terms, can we use $.get() to fetch a different page on the same website and transfer the PHP/Javascript cookies with ...

Steps for organizing a particular key in a map

I need assistance sorting my map based on the "time" value, but so far, I haven't been successful in finding a solution after searching online extensively. If anyone has any insights or recommendations, please share them with me. This is how my Map ...

Validating passwords using Vuetify

I am implementing password validation on my form using Vuetify validation rules: passwordRules: [ v => (v && v.length >= 1 && v.length <= 10) || 'Password length should be between 1 and 10', v => (v && v.l ...

Looking to decrease Cumulative Layout Shift (CLS) on the NextJS website for enhanced performance

I have chosen to use NextJS with Mantine for my website development. Utilizing createStyles, I have added custom stylings and incorporated various mantine components into the design. After deploying the site on Vercel, I discovered that all performance me ...

Using AngularJS to auto-populate additional fields after selecting an option from the typeahead autocomplete feature

Just starting with AngularJS and finally figured out how to implement Auto-complete in Angularjs. Now, when a user selects a value from the auto-complete, I want other fields to be populated based on that selection. For example, upon loading the screen, d ...