Search code examples
apivue.jsvuejs2twitchtwitch-api

Axios data not being carried over to data when mounted in Vue


I'm trying to call data from the Twitch IGDB API (with this we use POST instead of GET) with axios calls in Vue 2, but it's not working like I expect it to. I can log the access_token, but not the data from the fetch request.

I've made a separate file with the API requests which I'm imported in a Vue component, which looks like this:

import axios from "axios";

// Variables for Twitch Authorization
const client_id = process.env.VUE_APP_CLIENT_ID;
const client_secret = process.env.VUE_APP_CLIENT_SECRET;
const grant_type = "client_credentials";
const cors_server = "process.env.VUE_APP_CORS_ANYWHERE_SERVER";

// Get access token from Twitch Dev Account
export async function getAccessToken() {
  try {
    const response = await axios.post(
      `https://id.twitch.tv/oauth2/token?client_id=${client_id}&client_secret=${client_secret}&grant_type=${grant_type}`
    );
    const data = await response.data.access_token;

    return data;
  } catch (error) {
    console.log("Error: ", error);
  }
};

// Call Games from API
export function getGames(accessToken) {
  axios({
    url: `${cors_server}https://api.igdb.com/v4/games`,
    method: 'POST',
    headers: {
        'Accept': 'application/JSON',
        'Client-ID': client_id,
        'Authorization': `Bearer ${accessToken}`,
    },
    data: "fields *;",
  })
  .then(res => {
    console.log(res.data);
    return res.data;
  })
  .catch(error => {
    console.error(error);
  });
};

I've imported this into the component like this:

import { getAccessToken, getGames } from "./api_requests";

I've defined the data like this:

data() {
    return {
      games: null,
      accessToken: '',
    }
  },

And am calling the data in mounted like this.

  // Calling data from IGDB
  async mounted() {
    this.accessToken = await getAccessToken();
    getGames(this.accessToken).then(res => {
      this.games = res;
      console.log(this.games);
    });

I've tried different ways to call getGames in mounted but I just can't get it to save in the data correctly. Should I be calling this a different way? Is importing it causing problems? Should I make a method inside the component instead?


Solution

  • You're almost there. getGames() needs to return axios() so that the caller can receive the value of the response data:

    export function getGames(accessToken) {
      return axios({/*...*/})
    }
    

    Then the caller could just await it:

    async mounted() {
      this.games = await getGames(this.accessToken)
    }