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

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.

Prerequisites:

Steps to Create the React Application And Installing Module:

Step 1: Create a 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

The updated dependencies in package.json file will look like:

"dependencies": {
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4",
}

Approach: 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.
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;
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;
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;

Step to run the application: To start the application on your system, run the following command:

npm start

Output:




Reffered: https://www.geeksforgeeks.org


ReactJS

Related
How to pass property from a parent component props to a child component ? How to pass property from a parent component props to a child component ?
How to setup 404 page in React Routing ? How to setup 404 page in React Routing ?
Create a text to speech application using ReactJS Create a text to speech application using ReactJS
How to specify a port to run a create-react-app based project ? How to specify a port to run a create-react-app based project ?
Why to get &quot;Router may have only one child element&quot; warning ? Why to get &quot;Router may have only one child element&quot; warning ?

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
12