Consuming a REST API ( Github Users ) using Fetch - React Client
Last Updated :
25 Jul, 2024
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 StructureThe 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:
Similar Reads
Consuming a GraphQL API using fetch - React Client In this article, we will learn to develop a React application, which will fetch the data from a public GraphQL API using Fetch. We will use The Movie Database Wrapper ( TMDB ) API to fetch the shows available with name/keyword. You can find the API reference and source code links at the end of this
5 min read
How to Create RESTful API and Fetch Data using ReactJS ? React JS is more than just an open-source JavaScript library, it's a powerful tool for crafting user interfaces with unparalleled efficiency and clarity. One of React's core principles is its component-based architecture, which aligns perfectly with the Model View Controller (MVC) pattern. React com
5 min read
Consuming a Rest API with Axios in Vue.js Many times when building an application for the web that you may want to consume and display data from an API in VueJS using JavaScript fetch API, Vue resource, jquery ajax API, but a very popular and most recommended approach is to use Axios, a promise-based HTTP client. Axios is a great HTTP clien
2 min read
GET and POST Requests using Fetch API with Custom HTTP Library This tutorial covers the basics of using the Fetch API to perform GET and POST requests within a custom HTTP library. Wiasynchronous operations and handling JSON data, you can effectively fetch data from remote APIs and submit data to servers. This approach gives you greater control and flexibility
3 min read
Different ways to fetch data using API in React API: API is an abbreviation for Application Programming Interface which is a collection of communication protocols and subroutines used by various programs to communicate between them. A programmer can make use of various API tools to make its program easier and simpler. Also, an API facilitates pro
4 min read
Build a Random User Generator App Using ReactJS In this article, we will create a random user generator application using API and React JS. A Random User Generator App Using React Js is a web application built with the React.js library that generates random user profiles. It typically retrieves and displays details like names, photos, and contact
4 min read