Home > Mobile >  Can't set my Aurelia apps response when making an API Request with Axios
Can't set my Aurelia apps response when making an API Request with Axios

Time:05-16

I am trying to set my App's constructor object to the response made from an axios request when clicking on a button in my app but I keep getting this error

app.js:25 TypeError: Cannot set properties of undefined (setting 'response'): at app.js:22:17

I am guessing it is a scoping issue but I have no idea how to fix it ?

import Axios from "axios";
const axios = require("axios");

export class App {
  constructor() {
    this.response = [];
    this.testing = "";
  }

  test() {
    const options = {
      method: "GET",
      url: "https://omgvamp-hearthstone-v1.p.rapidapi.com/cardbacks",
      headers: {
        "X-RapidAPI-Host": "omgvamp-hearthstone-v1.p.rapidapi.com",
        "X-RapidAPI-Key": "80ae24591emshdc5de82055364cfp1aaebcjsn7ebda73c7aaf",
      },
    };

    Axios.request(options)
      .then(function (response) {
        return (this.response = response.data[0]);
      })
      .catch(function (error) {
        console.error(error);
      });
  }
}

Any help would be greatly appreciated :)

Thanks Guy

CodePudding user response:

You are doing it wrong expecting axios to return value. Also you need make axios call in async. And whatever value axios return can be return by test function.

try below code.

export class App {
    constructor() {
        this.response = [];
        this.testing = "";
    }

    async test() {
        const options = {
            method: "GET",
            url: "https://omgvamp-hearthstone-v1.p.rapidapi.com/cardbacks",
            headers: {
                "X-RapidAPI-Host": "omgvamp-hearthstone-v1.p.rapidapi.com",
                "X-RapidAPI-Key": "80ae24591emshdc5de82055364cfp1aaebcjsn7ebda73c7aaf",
            },
        };

        this.response = await axios.request(options)
            .then(function (response) {
                return response.data[0];
            })
            .catch(function (error) {
                console.error(error);
            });
    }
}
  • Related