part_2 access data from an external api - b05313fsldsp/web-for-kusapi GitHub Wiki

In the code above, gitHubUrl is a variable containing the GitHub API URL for the username deekshasharma. It's declared as a const because this value will not change. The State Hook below will allow the use of state in the function component without writing a separate class component. userData is an object that is initially empty (useState({})). Once the data is fetched from the network, it will contain the user data (name, location, blog, and company). setUserData is equivalent to writing this.setState() to update the component state with the value of userData.
const [userData, setUserData] = useState({});
Next is the Effect Hook, which will allow you to perform side effect operations such as fetching data, clean up, or DOM manipulation. useEffect() takes as argument a function that will execute after the first render and after every component update. So this function is an apt place to call the getGitHubUserWithFetch() function, whose job is to get the user data from GitHub API and update the component. Passing a second argument to useEffect is optional. Passing an empty array [] ensures this effect will run just once; otherwise, it will run after every render.
useEffect(() => {
  getGitHubUserWithFetch();
}, []);
getGitHubUserWithFetch() is an async function without implementation. We will write code inside this function shortly. Finally, the component returns a header containing the text "GitHub User Data" and the user data (name, location, blog, and company) rendered inside a
element.
return (
  <div className="App">
    <header className="App-header">
      <h2>GitHub User Data</h2>
    </header>
    <div className="user-container">
      <h5 className="info-item">{userData.name}</h5>
      <h5 className="info-item">{userData.location}</h5>
      <h5 className="info-item">{userData.blog}</h5>
      <h5 className="info-item">{userData.company}</h5>
    </div>
  </div>
);

Replace the contents in your src/App.css with the code below. The existing styles are slightly changed and new ones are added to display user data on the web page.

.App {
  text-align: center;
}

.App-header {
  background-color: #282c34;
  min-height: 10vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  font-size: calc(10px + 2vmin);
  color: white;
}

.user-container {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
}

.info-item {
  width: 15vw;
  height: 5vh;
  padding: 2em;
  border: 2px solid rgb(159, 12, 22);
  align-self: center;
  background-color: #63b7af;
  border-radius: 2em;
}
Get Data Using Fetch API - Here is how to implement the getGitHubUserWithFetch() function. The code below uses async/await so that asynchronous code is readable and appears to be executing synchronously.

Though async functions always return a Promise, there is no need to return a value in this case since setUserData() is called with the resulting jsonData within the function itself.

Now comes the fetch() API, which takes as argument a URL, makes a network request to that URL, and returns a Promise that resolves to a response object.

The await keyword in front of the fetch() function pause the code until fetch() returns a fulfilled Promise, after which it returns the resolved value response.

The response is then parsed into a JSON using the json() method, which also returns a Promise that resolves to the JSON object jsonData. The use of await yet again pauses the code until the response is parsed to JSON. Then setUserData() is called with the resulting JSON object jsonData. It updates the state of the component with GitHub user data.

const getGitHubUserWithFetch = async () => { const response = await fetch(gitHubUrl); const jsonData = await response.json(); setUserData(jsonData); }; js To verify your code changes, open your browser to http://localhost:3000 and you should be able to view the GitHub user details rendered as React components for the username deekshasharma.

Get Data Using Axios The second approach to fetch the data from the GitHub API is by using the Axios library. You already installed the dependency in your project. All you need now is to import it inside src/App.js. So go ahead and add this import.

import axios from "axios"; js Add another function, getGiHubUserWithAxios(), in your component, which use Axios. Since it is a Promise-based library, you can seamlessly replace Promise.then() with async/await.

the get() method of the library takes as argument a URL and makes an http request to that URL. It then automatically transforms the response to JSON, which you can get from its data property. Once the data is received, the state of the component is updated via the setUserData() function.

const getGiHubUserWithAxios = async () => { const response = await axios.get(gitHubUrl); setUserData(response.data); }; js Inside your component, make sure you call getGiHubUserWithAxios() instead of getGitHubUserWithFetch() inside useEffect().

useEffect(() => { getGiHubUserWithAxios(); }, []); js Verify your code changes in the browser at http://localhost:3000, and you should see the data rendered in a React component for the username deekshasharma.

Conclusion You now understand how to get data for your React components from an external API using fetch and axios. Both achieve the same objective and you can choose either of the two.

However, keep in mind that axios should be added as an npm dependency, whereas fetch is available out of the box as a web API. Another difference is that axios returns you the transformed JSON data, but with fetch you need to parse the response and extract the JSON before passing it to React components.

The code for this guide is available at GitHub.

These additional resources are worth reading if you want to learn more:

Understanding Effect Hook in React Working with State Hook in React How Fetch API works Axios on Browser

LEARN MORE We use cookies to make interactions with our websites and services easy and meaningful. For more information about the cookies we use or to find out how you can disable cookies, click here.

Disable cookies

Accept cookies and close this message

⚠️ **GitHub.com Fallback** ⚠️