``If you're looking to retrieve, modify, and display information in your Vue application with the help of

I'm facing an issue where I am trying to retrieve data using the axios get request and then updating it based on the response of another axios get request. However, I am unable to display the data from the second request.

The following is a snippet of the code:

// api.js
  // fetch items - first API call
  fetchItems() {
    const ITEMS_ENDPOINT = `${ROOT_URL}/items`;
    return axios.get(ITEMS_ENDPOINT, config);
  },

  // fetch items info - 2nd API call
  fetchItemsInfo(itemId) {
    const ITEMS_INFO_ENDPOINT = `${ROOT_URL}/items/${itemId}`;
    return axios.get(ITEMS_INFO_ENDPOINT, config);
  },

// Vue component
  methods: {
    async fetchItems() {
      const res = await api.fetchItems();
      this.items = res.data;
      console.log(this.items);

    },

    updateItems() {
      this.items.forEach(async (item) => {
          const itemId = item.id;
          const res = await api.fetchItemsInfo(itemId);
          const info = res.data;
          console.log(info);

          if (item.id === info.id) {
            item.x = info.x;
            console.log(item);
          }
      });
    },
  },

  async created() {
    await this.fetchItems();
    this.updateItems();
    console.log(this.items);

<ul>
      <li v-for="(item, index) in items" :key="index">

        {{ item.id }} || {{ item.a }} || {{ item.x }} 
      </li>
</ul>

The issue here is that only the data from the first API call is being displayed, not from the second call. Logging the data within the created hook shows the expected output in the console. When utilizing a click method to trigger the updateItems function, the data renders correctly. However, I want it to load on page load.

The behavior remains unchanged even when updating the Vuex state from updateItems and rendering the state getters.

How can I ensure that the data from the second call is also rendered?

Thank you in advance.

Answer №1

Your current issue stems from attempting to add new properties to a reactive item, which is not effective. To resolve this, consider recreating the entire object rather than adding new properties.

updateItems() {
  this.items = this.items.map(async item => {
    const { data: info } = await api.fetchItemsInfo(item.id);
    return {
      ...item,
      ...info
    }
  });
},

If you are aware of the property names, another approach could be using Vue.set.

Vue.set(item, 'property1', info.property1)
Vue.set(item, 'property2', info.property2)
etc...

This solution should address your needs, although I recommend considering optimizing by including the details in the initial fetch items call rather than sending additional requests per item.

Answer №2

Following the recommendation from Thakur Karthik, I was able to implement a workaround. I switched from using forEach to utilizing a for..of loop, created a new array in data, and then copied the contents of this.items into the new array. The revised section of the code now looks like this:

// .... 
    async updateItems() {
      for (const item of this.items) {
        const itemId = item.id;
        const res = await api.fetchItemsInfo(itemId);
        const info = res.data;
        console.log(info);
        // console output {id:1, x:2}

        if (item.id === info.id) {
          item.x = info.x;
          console.log(item);
          // console output [{id:1, a:1, x:2}]
        }
        // create a new array and copy items to it
        this.updatedItems = this.items;
      }

An alternative solution that I discovered involves invoking a Vuex store action to update the state of items instead of performing a direct copy. The modified code snippet is as follows:

    async updateItems() {
     
        //.... rest of the code

        // call a vuex store action (`setItems`) to update the state items
        this.setItems(this.items)
      }

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

When setting an empty URL with Fabricjs' setBackgroundImage function, a null reference error occurs in the _setWidthHeight

Recently, I stumbled upon an article detailing a method to clear the background of a fabric canvas... canvas.setBackgroundImage('', canvas.renderAll.bind(canvas)); In the development of my online design tool which utilizes Fabricjs 1.4.4, I have ...

When utilizing Ionic with Angular, it is difficult to access the hardware back button on mobile devices that have buttons located within the display/screen

When trying to access the hardware back button in my app, I encountered an issue where I couldn't produce an alert message to the user before the app closed. After posting a question on Stack Overflow (link of the question) and receiving help from the ...

What is the best way to send pg-promise's result back to the controller in Express?

While working with Ruby on Rails (RoR), I am familiar with the MVC (Model-View-Controller) concept. In this framework, the controller is responsible for receiving data from the model, processing it, and rendering the view. An example of this structure look ...

HtmlWebpackPlugin can cause issues with loading relative path files on websites that are not located in the root directory

I have set up webpack and the HtmlWebpackPlugin to automatically include bundled js and css files in an html template. new HtmlWebpackPlugin({ template: 'client/index.tpl.html', inject: 'body', filename: 'index.html' ...

What steps can be taken to customize the default keyboard shortcuts functionality in Swiper.js?

I am trying to customize the functionality for left/right keys in Swiper.js but I am unable to find a way to do this through the API () It seems that the API only allows you to disable/enable default actions: mySwiper.keyboard.enabled // Whether th ...

Utilizing SlickGrid and DataView for calculating totals efficiently without the need for grouping

I am attempting to utilize Slick Grid and DataView to calculate column totals similar to the example shown here: . However, I do not want to group my rows. Therefore, I attempted not passing a getter and formatter into the dataView.setGrouping(..) method. ...

Create additional object property and include in current object's properties dynamically

I have a JSON object that looks like this: "highChart":{ "xAxis":{ "categories":[ "SYN 13 ", "Settlement", "Service Interaction", "FNOL", ...

Spin an object on a stationary axis

https://i.sstatic.net/8dT9W.gif Is there a method to create a similar effect using CSS, JS, or GSAP? ...

What is the best way to save the data received from createApi into the Redux store?

Currently, I am faced with the challenge of storing user data (such as name, email, etc.) obtained through the createApi function into Redux store. However, I'm unsure of the best practice to achieve this. In my userApi.js file: export const userApi ...

Is there a way to streamline this query code that seems overly complex?

Could someone please assist me in simplifying this code? I am trying to shorten or simplify the query code by using a stored procedure, but I still need to include the details inside the "()" parentheses. I am new to Node.js and would appreciate any help. ...

Issue with Karma and angular-mocks: The error message "TypeError: 'undefined' is not an object (evaluating 'angular.mock = {}')" is being shown

I am facing an issue while writing unit tests using Karma + Jasmine. The problem arises with angular-mocks when I run grunt test, resulting in the following error message: PhantomJS 1.9.8 (Mac OS X) ERROR TypeError: 'undefined' is not an ob ...

Contrast between the expressions '$(<%= DDL.ID %>) and $('<%= DDL.ID %>')

I spent hours trying to attach an event to a drop-down list with no success. I even sought help in a JavaScript chat room, but couldn't find a solution. However, by randomly attempting the following code: $('<%= ddl.ID %>').bind(&apos ...

What is the best way to turn off default CSS styling in KendoUI?

I am facing an issue in my application where I am using global CSS definitions for "INPUT", "SELECT", and other elements. The problem arises when I try to incorporate KendoUI widgets, as they override my default CSS styles. For instance, my CSS code looks ...

What is the best way to format or delete text enclosed in quotation marks within an anchor tag using CSS or JavaScript?

I have encountered an issue with a dynamically generated login form. When I select the 'Forgot Password' option, a new 'Back to Login' message appears along with a separating '|' line. Removing this line is proving challenging ...

Featherlight is experiencing issues with running Ajax requests

I'm currently working on integrating an ajax photo uploading script into a Featherlight lightbox, but I'm running into issues! If anyone could help me figure out what's going wrong, that would be greatly appreciated. I've already includ ...

Transforming varied JavaScript objects into a serial form

In my application, there is a concept of an interface along with multiple objects that implement this interface in various ways. These objects are created using different factory methods, with the potential for more factories to be added as the application ...

Creating a JSON object from text using JavaScript is a straightforward process

Looking to generate an object using the provided variable string. var text ='{"Origin":"Hybris","country":"Germany","Email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfem ...

Is there a method to access a website, trigger JavaScript functions, and subsequently retrieve the HTML content using PHP?

I am currently exploring options to access a webpage, execute JavaScript functions on it (thus altering the HTML content), and eventually save the modified version of the page. I'm uncertain if this approach is feasible, and if not, are there alternat ...

The replacer argument of the JSON.stringify method doesn't seem to work properly when dealing with nested objects

My dilemma is sending a simplified version of an object to the server. { "fullName": "Don Corleone", "actor": { "actorId": 2, "name": "Marlon", "surname": "Brando", "description": "Marlon Brando is widely considered the greatest movie actor of a ...

Utilizing Ajax to dynamically load files within the Django framework

My current project involves working with Django, specifically a feature that requires loading a file and displaying its content in a textarea. Instead of storing the file on the server side or in a database, I am exploring the use of AJAX to send the file ...