Search code examples
javascriptasync-awaites6-promisegithub-api

Using Fetch to Return GitHub User Data


Forgive the ignorance, I'm not great with JavaScript (yet). I'm trying to fetch public user data from GitHub and display it on my personal portfolio. Currently I have the code below:

 getData(url) {
  return fetch(url);
}
const userData = getData("https://api.github.com/users/userName");

userData
  .then((response) => response.json())
  .then((response) => console.log(response))
  .catch((error) =>
    console.log("There was an error fetching the data: " + error)
  );

  console.log(userData)

The response I get is the JSON with the user data but when I console.log(userData) I get Promise { <state>: "pending" } as the response.

Also, I can see that there is an id in the initial response but when I console.log(userData.id) I get undefined.

I've read the GitHub API docs and watched a few videos on Promises but I can't seem to get my code to work correctly.

Thanks for taking the time to look at this and any help with this is greatly appreciated!


Solution

  • It is because userData is a promise. If you try using async/await (documentation is available here) you'll be able to synchronously get the data.

     const getData = async (url) => {
       try {
         const data = await fetch("https://api.github.com/users/:user_name");
         console.log(data.json());
         return data;
       } catch (e) {
         console.log("There was an error fetching the data: " + error)
       }
     }