Consuming a REST API ( Github Users ) using Fetch - React Client - GeeksforGeeks

09 Nov, 2021
In this article you will learn to develop a React application, which will fetch the data from a REST API using Fetch. We will use GitHub Users API to fetch the user’s public information with their username. You can find the API reference and source code links at the end of this article. 
Before moving onto the development part, to initialize a simple react application you can follow the steps mentioned below: 
Step 1: Create React application.
npx create-react-app foldername
Step 2: Move into the project folder.
cd foldername
Step 3: Create a components folder and now Project Structure will look like: 
Project Structure
Custom components resides in the components folder, with everything put together in the MainComponent.js, we will place this component inside App.js, which itself goes under “root” DOM node and everything inside this node will be managed by React DOM.
We are going to develop three components:
Main Component: Responsible for fetch operation and state changes in the application.
Search Bar: A search bar to get the user input for GitHub username.
UserInfoCard: A reusable component to display the GitHub user information.
Step 4: In the MainComponent.js component, we have two state variables, username ( input from the user ) and userData ( response from the REST API ). We need to fetch the user data, every time there is an update to the username.  To achieve this, we are going to use useEffect hook from React. 
Javascript
const [username, setUsername] = useState("");const [userData, setUserData] = useState({});  useEffect(() => {     getUserData(); }, [username]);
Step 5: Now to get the response from GitHub users API, we are going to make a GET request using Fetch, which will be the role of getUserData() function. 
 
Javascript
var gitHubUrl = `https://api.github.com/users/${username}`;  const getUserData = async () => {        const response = await fetch(gitHubUrl);        const jsonData = await response.json();        if (jsonData && jsonData.message !== "Not Found") {            setUserData(jsonData);            console.log(jsonData)        }        else if (username !== "") {            console.log('Username does not exist');        }        else {            setUserData({})        }    };
getUserData() is an asynchronous function, in which fetch(gitHubUrl) makes the request and returns a promise. When the request is complete, the promise is resolved with response object. This object is basically a generic placeholder for various response formats. response.json()  is used to extract the JSON object from the response, it returns a promise, hence the await. 
So finally, our MainComponent.js file is looks like:
Javascript
import React, { useState, useEffect } from "react";import SearchBar from "./SearchBar";import UserInfoCard from "./UserInfoCard";  function Main() {    const [username, setUsername] = useState("");    const [userData, setUserData] = useState(Object);          useEffect(() => {        getUserData();    }, [username]);      var gitHubUrl = `https://api.github.com/users/${username}`;      const getUserData = async () => {        const response = await fetch(gitHubUrl);        const jsonData = await response.json();        if (jsonData && jsonData.message !== "Not Found") {            setUserData(jsonData);            console.log(jsonData)        }        else if (username !== "") {            console.log('Username does not exist');        }        else {            setUserData({})        }    };          return (        <div>            <SearchBar username={username}                 setUsername={setUsername} />            <UserInfoCard userData={userData} />        </div>    );}  export default Main;
Step 6: Now, moving on to the SearchBar component, which serves the purpose of receiving the user input for username. It is a simple component, with an input field of text type. On any change, it fires of the setUsername with the updated value.
Javascript
import React from "react";  function SearchBar({username, setUsername}){      const onChange = (e) =>{        setUsername(e.target.value)    }    return(        <div className="searchbar">        <input             placeholder="Search"            type="text"             onChange={(event) => {onChange(event)}}            onKeyUp={(event) => {onChange(event)}}            onPaste={(event) => {onChange(event)}}        />        </div>    );}  export default SearchBar;
Step 7: Our last component, is a reusable UI component, which is basically a Card Component that receives userData as props, and just displays it in any chosen format. You can tweak the App.css file to understand the various design aspects. 
Javascript
import React from "react";  function UserInfoCard({ userData }) {    return (        <div className="datacontainer">            {userData.avatar_url ? (<div className="dataitem">               <img src={userData.avatar_url}                alt="avatar" /></div>) : (<div></div>)}            {userData.login ? (<div className="dataitem">Login:             {userData.login}</div>) : (<div></div>)}            {userData.name ? (<div className="dataitem">            Name : {userData.name}</div>) : (<div></div>)}            {userData.blog ? (<div className="dataitem">            Blog: {userData.blog}</div>) : (<div></div>)}        </div>    );}  export default UserInfoCard;
That is all, with these three components put together, completes our React application, which you can download from the source code link provided below, and run it on your system. Source code does include an extra component, to store the retrieved data in Local Storage, which  was not covered in this article. So if you’re interested, go ahead and check that out as well. 
Step to run the application: To start the application on your system, run the following command:
npm start
Output:
GitHub Users API: https://docs.github.com/en/rest/reference/users
Fetch API: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API
Source Code: https://github.com/notnotparas/github-users-api
React-Questions
Web-API
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to navigate on path by button click in react router ?
ReactJS useNavigate() Hook
How to set background images in ReactJS ?
How to check the version of ReactJS ?
How to create a table in ReactJS ?
Express.js express.Router() Function
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React