Search code examples
javascriptvue.jses6-promise

Async/Await in Vue with mount() hook not working


I'm using vue 2.5 and I have a mount hook that calls a module that fetches an API nedpoint and returns it to vue component via the mount hook. I have previously asked question and been referred to post return response from async call and have followed examples in answer but still my Vue component variable shows as undefined when component rendered. Here is my code:

/modules/retrieveLeagueLeaders

 const getLeagueLeaders =  (url, params) => {
    fetch(url + new URLSearchParams(params), {
      method: "get",
      headers: {
        Authorization:
          "Basic ****=",
      },
    })
      .then((response) => response.json())
      .then((data) => {
        let leagueLeaders = data;
        console.log(
          "leagueLeaders is %s",
          leagueLeaders.cumulativeplayerstats.playerstatsentry[0].player
            .LastName
        );

        return leagueLeaders;
        
      });

    
  };

  module.exports = getLeagueLeaders;

and the Vue code:

/src/components/leagueLeaders
 mounted: async function () {
      this.qbLeaders = await getLeagueLeaders(this.fetchQbUrl, this.params);
      console.log("qBLeaders is %s", this.qbLeaders);
    },
  })

Console shows

qBLeaders is undefined nflLeagueLeaders.js:28
leagueLeaders is Wilson getLeagueLeaders.js:17

I have tried wrapping whole module in a Promise but still it does not return a promise when run. Is there something to how I am using Async/Await in Vue mount hook that is incorrect? I could really use some guidance as I have tried all suggestions in posts to no avail. Thanks in advance..


Solution

  • Don't try to return a value inside a callback, this doesn't work, you could simply return the promise :

    const getLeagueLeaders =  (url, params) => {
       return  fetch(url + new URLSearchParams(params), {
          method: "get",
          headers: {
            Authorization:
              "Basic ****=",
          },
        })
          .then((response) => response.json())
             
      };
    
      module.exports = getLeagueLeaders;