What could be causing my function to not wait for the API response?

I am currently working on a class that utilizes an API, where all the requests are handled within this class.

export default class API {
    constructor() {
        this._instance = {};
    }

    get instance() {
        return this._instance;
    }
    
    set instance(newInstance) {
        this._instance = newInstance;
    }


    login(username, password) {
        return axios.post("thisisanexample.com/login", {
        username: username,
        password: password,
        });
    }

    createInstance(token) {
        this._instance = axios.create({
           baseURL: "thisisanexample.com",
           timeout: 1000,
           headers: { Authorization: "Bearer " + token },
        });
    }

}

Within a Vue Component, I incorporate this class.

import Api from "../api.js"

export default{
    name : "login",
    
    data : () => ({
     API : {
       instance: null,
     },
    }),
    
    mounted() {
       this.API = new Api();        
    }

    methods : {
    
       login(){
          this.API.login("username", "password").then((r) => {
              this.API.createInstance(r.data.token);
          });
       }

       isInstanceWorking(){
          console.log(this.API.instance);
       }    
    }


Upon calling the function isInstanceWorking() for the first time (on a button click event), it returns an empty object. However, when clicked again, it displays an instance. This is likely due to the fact that the initial call did not wait for the response, but the subsequent one did.

After conducting some investigation, I have learned that using keywords like await, async, or then might help resolve this issue. Despite my attempts to utilize them, I have not been successful.

My question now is, how can I ensure that my function waits for a response before proceeding? What could be the error in my approach?

In the future, I plan to integrate additional requests to my API such as this.games = this.API.games, which will return the games for the current instance.

Answer №1

createAPIInstance(token) {
    this._instance = axios.create({
           baseURL: "thisisanexample.com",
           timeout: 1000,
           headers: { Authorization: "Bearer " + token },
        })
}
import Api from "../api.js"

export default{
    name : "loginPage",
    
    data : () => ({
     API : {
       instance: null,
     },
    }),
    
    mounted() {
       this.API = new Api();        
    }

    methods : {
    
       loginUser(){
          this.API.login("username123", "password123")
             .then((r) => {
                  return this.API.createAPIInstance(r.data.token);
             })
             .then(()=>{
                  //call isAPICreated
                  return this.API.getGames()
             })
             .then(r=>{
                  console.log(r);// games data
             })
       }

       isAPICreated(){
          console.log(this.API.instance);
       }    
    }

Answer №2

Consider trying to output the instance within the same .then chain inside the login function.

login() {
    this.API.login("username", "password").then((r) => {
        this.API.createInstance(r.data.token).then(() => {
            console.log(this.API.instance);
        )};
    });
}

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

vuejs Creating a model for a list of radio items

Is there a way to define a v-model for a framework7-vue radio list item element? Checkboxes & Radios Vue Component <f7-list-item radio name="my-radio" v-model="method.val" value="ISNA" title="Islamic Society of North Ame ...

Unexpected behavior occurs when using JSON.parse

When attempting to process a json request sent via post, I encountered an error while using JSON.parse: Uncaught SyntaxError: Unexpected token m in JSON at position 2 at JSON.parse () at :1:19 The following code snippet triggers the error: ...

Adding a class using jQuery based on whether a section is visible or hidden on the screen

Seeking advice on the best approach to take. Division 1 or section - Apply style 1 if division 1 is currently visible on the screen. Division 2 or section - Apply style 1 if division 2 is currently visible on the screen. Division 3 or section - Apply st ...

Polymer - the content tag within core-animated-pages does not properly adjust its height

My goal is to give each element on my list 2 pages or views, with generic content (<content></content>) for each. However, I'm running into an issue where the elements are overlapping when using core-animated-pages to wrap the generic cont ...

Error encountered during sequelize synchronization: SQL syntax issue detected near the specified number

Four Sequelize Models were created using sequelize.define();. Each model is similar but with different table names. To avoid manual creation of tables in MySQL cli, the decision was made to use sequelize.sync() in the main index.js file to allow Sequelize ...

Convert a vertical JSON format into a horizontal one using jQuery

I have a JSON data structure as shown below: var data = [ { "year": 2013, "month": 10, "week": 41, "changes": 1590 }, { "year": 2013, "month": 10, "week": 42, "changes": 0 }, { "year": 2013, "month": 10, "week": 43, "changes": 20 ...

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 = " ...

Unable to utilize Vuex Getter with parameters

I have a Vuex Store setup like this const config = { featureA: { isEnabled: true, maxUser: 2 }, featureB: { isEnabled: false, maxData: 5 }, } const actions = { getDataCompany(context, payload) { return new Promise(async (resolve, reject) => { ...

Extension in Chrome operating in the background while the pop-up is out of sight

As a beginner, my goal was to develop a Chrome Extension. However, I am facing a roadblock as I am unsure how to set up my extension to run in the background. Despite conducting research to find a solution, I have been unable to find a suitable answer to ...

Arranging an upgrade within a task management app

I'm currently in the process of developing a task management app with AngularJS, Node, Express, and MongoDB. Everything seems to be falling into place except for the update functionality. I'm struggling with implementing this feature, especially ...

The file input modification event is disregarded if the identical filename is selected for upload

In my Vue.js application, I am utilizing Vuetify's v-file-input component. The file uploaded is connected to formData.file and its validation is controlled by the rules prop. <v-file-input :rules="fileValidationRules" v-model="fo ...

Transmitting information return from php

I followed a tutorial on using ajax and php to send/retrieve data from my mysql database. Here is the ajax part of it: <script> function showUser(str) { if (str=="") { ...

Forwarding website to a document

Imagine a webpage featuring a table where users have the option to download it as an Excel sheet. This option is presented in the form of a button that triggers the submission of a form containing the necessary parameters to create the same report, but in ...

In Bootstrap, it is important that the number of indicators in the carousel matches the number of images displayed

I have successfully created a Carousel Slider with the help of Bootstrap and Advanced Custom Fields. Everything is functioning well, but I am facing an issue with making the Indicators correspond to the number of images I have. Each indicator needs to be s ...

Storing a Global Variable in Mocha.js

Currently, I am utilizing Mocha.js for testing within a Node.js - Express.js - Firebase setup. To access the API endpoints, I require a token from Firebase. Despite implementing a before hook across all my files, after conducting around 250 tests that may ...

Ways to dynamically eliminate focus around text inputs

I have created an HTML page and here is the link to it: https://i.sstatic.net/n8UdU.png My main goal is to remove the black border around the text input on this page. The challenge I am facing is that the 'things to do' list is generated dynamic ...

Cannot load local JSON file via AJAX in ReactJS

Below is the React component I am currently working with. import React, { Component } from 'react'; class GraphView extends Component { constructor(props){ super(props); this.state = { datajson: &apo ...

Unable to display the value of my array in JSON encoded PHP due to it being undefined

In my cart.php file, I have encoded an array to JSON and returned it to an AJAX function: $data = array(); $data['total'] = '10000'; $data['quantity'] = '10'; echo json_encode($data); In my index.php f ...

The functionality of scope.$observe is unavailable within an AngularJS Directive

Consider the snippet below: appDirectives.directive('drFadeHighlight', ['$animate', '$timeout', function ($animate, $timeout) { return { scope: { isWatchObject: '=' }, restric ...

Learn the steps for incorporating a fresh item into a table from a pop-up interface with angularjs

I have been working on a simple customers table that includes information such as name, lastname, and age. I have successfully created a function that allows users to add a new customer, which is working fine. Additionally, I have implemented a pop-up wind ...