Jonathan Sexton
Jonathan Sexton

Reputation: 139

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!

Upvotes: 3

Views: 1479

Answers (1)

zlwaterfield
zlwaterfield

Reputation: 841

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)
   }
 }

Upvotes: 4

Related Questions