Vue component's data remains stagnant within created() hook

I'm currently working on transforming the API response to make it more suitable for constructing two tables. Despite adding debugging outputs within my function in created(), I am witnessing the desired output temporarily, but upon further examination, it appears that the data has not actually changed. There seems to be some strange behavior possibly related to this, although I have been unable to resolve it.

This is what my current code looks like:

export default {
  name: 'component',
  data: function() {
      return {
        tableOne: [],
      }
  },
  computed: {
      ...mapState([
        'modal'
      ])
  },
  created() {
  api.get_appointments()
      .then(appointments => {
          for (var i = 0; i < appointments.length; i++) {            
              this.tableOne.push(
                  {
                      tech: appointments[i].tech_name,
                      date: appointments[i].scheduled_date
                  }
              )
          }
      });
  },
};

The api.get_appointments() function implementation is as follows:

get_appointments() {
  return axios({
    method: "get",
    url: '/appointments'
  })
  .then(res => (res.data.data))
  .catch(error => {return error});
};

Answer №1

As the request is being made, the second console log appears before the request is completed. Consider utilizing async-await to handle this asynchronous process more effectively.

async created() {
  await api.get_appointments()
      .then(appointments => {
          for (var i = 0; i < appointments.length; i++) {            
              this.tableOne.push(
                  {
                      tech: appointments[i].tech_name,
                      date: appointments[i].scheduled_date
                  }
              )
          }
          // console.log(this.tableOne);
      });
  // console.log(this.tableOne);
  },

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

Middleware that handles form post requests quickly became overwhelmed and resulted in a RangeError

Currently, I am working with a form using ejs templates to collect data. When accessing the "/" route, my application renders the "main" view and utilizes a middleware to handle the form data. However, I encountered an error stating "RangeError: Maximum ca ...

What are the best ways to integrate markdown into my Vue.js projects?

Is there a way to utilize markdown within the context of vue.js instead of regular HTML paragraphs? ...

Learn to Generate a Mathematical Quiz with Javascript

For a school project, I am tasked with developing a Math Quiz which showcases questions one at a time. The questions vary in type, including Multiple Choice, Narrative Response, Image Selection, Fill in the blank, and more. I require assistance in creatin ...

Strategies for managing asynchronous forEach loops, inserting outcomes into a database, and displaying the finalized dataset

I want to achieve the following steps: Call an API resource Receive an array of records - [arr] Iterate over [arr] and execute a function which involves making another async call to an API for each item Create an object for each iteration that includes el ...

Using JavaScript to adjust the width of the table header

I have a table that I need to adjust the width of using JavaScript or jQuery. <div class="dataTables_scrollHeadInner" > <table class="table table-condensed table-bordered table-striped dataTable no-footer" > <thead ...

Leveraging Angular for REST API Calls with Ajax

app.controller('AjaxController', function ($scope,$http){ $http.get('mc/rest/candidate/pddninc/list',{ params: { callback:'JSON_CALLBACK' } }). success(function (data, status, headers, config){ if(ang ...

How to Implement Autoplay Feature in YouTube Videos with React

I'm having trouble getting my video to autoplay using react. Adding autoplay=1 as a parameter isn't working. Any ideas? Below is the code I am using. <div className="video mt-5" style={{ position: "relative", paddingBot ...

Navigate back to the parent directory in Node.js using the method fs.readFileSync

I'm restructuring the folder layout for my discord.js bot. To add more organization, I created a "src" folder to hold all js files. However, I'm facing an issue when trying to use readFileSync on a json file that is outside the src folder. Let&ap ...

Prevent scrolling in AngularJS model popups

When loading data for the first time in a model popup, the scroll bar is not displayed inside the popup. However, after performing a search function and filtering the data, the scroll bar appears inside the model popup. How can this issue be fixed? this ...

What is the best way to retrieve the value of an nth column in a table using

Is there a way to retrieve the value of a specific column in a table? For example, I want to get the value of the 2nd column. I have no trouble getting the first one using this method - it works perfectly fine. However, when I try to retrieve the value of ...

Experimenting with TypeScript code using namespaces through jest (ts-jest) testing framework

Whenever I attempt to test TypeScript code: namespace MainNamespace { export class MainClass { public sum(a: number, b: number) : number { return a + b; } } } The test scenario is as follows: describe("main test", () ...

Tips for choosing a visible element in Protractor while using AngularJS

I am working on a Single Page Application that contains multiple divs with the same class. My goal is to have protractor identify the visible div and then click on it. However, I keep encountering the error Failed: element not visible, which leads me to be ...

What is the correct method for accessing an array within an object that is nested inside an array within a JSON file in Angular?

In my Angular controller code, everything is functioning properly except for the $scope.Product. I am unable to access the array of product details. Here is the relevant code snippet: .controller('aboutCtrl', function ($scope, aboutService) { ...

Switching an element from li to div and vice versa using Jquery Drag and Drop

I am currently experimenting with the following: Stage 1: Making the element draggable from li to div upon dropping into #canvas Placing the draggable element inside #canvas Stage 2: Converting the draggable element from div back to li when dropped i ...

Using TinyMCE editor to handle postbacks on an ASP.NET page

I came up with this code snippet to integrate TinyMCE (a JavaScript "richtext" editor) into an ASP page. The ASP page features a textbox named "art_content", which generates a ClientID like "ctl00_hold_selectionblock_art_content". One issue I encountered ...

VueJs with typescript encounters issues with recursive child components, resulting in a warning stating "Unknown custom element" being thrown

I am currently working on a dynamic form that is generated by a DataTypeObject (dto). I have encountered an issue with a warning message while creating recursive components. This warning points to a list of components with the same type as their parent: ...

How to extract only the truthy keys from an object using Angular.js

I am looking to retrieve only the keys with a true value in the data object and display them in the console with the specified format: Object { Agent=true, Analytics / Business Intelligence=true, Architecture / Interior Design=false } The catego ...

Executing React Fetch API Twice upon loading the page

Double-fetching Issue with React Fetch API on Initial Page Load import React, { useState, useEffect } from 'react' import axios from 'axios'; import { Grid, Paper, TextField } from '@mui/material' import PersonOut ...

Save an HTML5 canvas element as a picture using JavaScript and specify the file extension

Is there a way to save an Html5 canvas element as an image file using Javascript? I've tried using the CanvasToImage library, but it doesn't seem to work for this purpose. You can view my current code on JsFiddle. <div id="canvas_container" ...

Developing a new React application with Access Control List (ACL) and encountering an issue with Casl

I've recently started working with casl and it feels like I might be overlooking something crucial. So, I created a file named can.js which closely resembles the example provided in the documentation: import { createContext } from 'react'; i ...