How to fetch data from APIs using Asynchronous await in ReactJS ?
Last Updated :
12 Jan, 2024
Fetching data from an API in ReactJS is a common and crucial task in modern web development. Fetching data from API helps in getting real-time updates dynamically and efficiently. API provides on-demand data as required rather than loading all data.
Prerequisites
Approach
To fetch data from APIs using Asynchronous await in ReactJS we will make an API request. Fetching data is an asynchronous process which means it does not update instantly and takes time to fetch the data. The await keyword enables the assignment to state le when data is available and is completely fetched.
API
APIs are basically a type of application that stores data in the format of JSON (JavaScript Object Notation) and XML (Extensible Markup Language). It makes it possible for any device to talk to each other.
Asynchronous Await
Async ensures that the function returns a promise and wraps non-promises in it. There is another word Await, that works only inside the async function.
Syntax
const fun = async () => {
const value = await promise;
};
Steps to create React Application
Step 1: Create a React application using the following command:
npx create-react-app foldername
Step 2: Move to the project directory using the following command:
cd foldername
Step 3: After creating the ReactJS application, Install the required module using the following command:
npm i axios
Project Structure:
Project StructureThe updated dependencies in package.json file will look like:
"dependencies": {
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"axios": "^1.6.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
}
Example: This example creates async function and use await to use data when it is completely fetched.
JavaScript
// Filename: App.js
import React, { useState, useEffect } from "react";
import axios from "axios";
function App() {
const [loading, setLoading] = useState(false);
const [posts, setPosts] = useState([]);
useEffect(() => {
const loadPost = async () => {
// Till the data is fetch using API
// the Loading page will show.
setLoading(true);
// Await make wait until that
// promise settles and return its result
const response = await axios.get(
"https://jsonplaceholder.typicode.com/posts/"
);
// After fetching data stored it in posts state.
setPosts(response.data);
// Closed the loading page
setLoading(false);
};
// Call the function
loadPost();
}, []);
return (
<>
<div className="App">
{loading ? (
<h4>Loading...</h4>
) : (
posts.map((item) => (
// Presently we only fetch
// title from the API
<h4>{item.title}</h4>
))
)}
</div>
</>
);
}
export default App;
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output:
Similar Reads
How to Fetch Data From an API in ReactJS? ReactJS provides several ways to interact with APIs, allowing you to retrieve data from the server and display it in your application. In this article, weâll walk you through different methods to fetch data from an API in ReactJS, including using the built-in fetch method, axios, and managing the st
8 min read
How To Fetch Data From APIs In NextJS? Fetching data from APIs in Next.js can be done using built-in methods like getServerSideProps, getStaticProps, or client-side fetching with useEffect. This flexibility supports both server-side and static data fetching.Prerequisites:NPM & NodeJSReactJSReact HooksReact RouterApproachTo fetch data
2 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
How to dispatch asynchronous actions using Redux Thunk? Asynchronous actions are very important in web development, particularly in tasks such as fetching data from API. Redux Thunk is a middleware using which you can write action creators that return a function instead of an object. This function can perform asynchronous operations and dispatch actions
3 min read
How to get single cache data in ReactJS ? We can use cache storage using window cache and in React JS to get single cache data. We can get single cache data from the browser and use it in our application whenever needed. Caching is a technique that helps us to store a copy of a given resource in our browser and serve it back when requested.
2 min read
How to Map Data into Components using ReactJS? Mapping data in react js component is a comman practice to render the lists and repeating elements. In this article, we will have a users data and we will map it to react components to display the users information in the react appPrerequisites:React JSNodejs and npmJavaScript Array mapApproachTo ma
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
How to get complete cache data in ReactJS? In React, we can get all cache data from the browser and use it in our application whenever needed. Caching is a technique that helps us to store a copy of a given resource in our browser and serve it back when requested.PrerequisitesReact JSCacheStorageApproachTo get all cache data in React JS defi
2 min read
How To Create a Delay Function in ReactJS ? Delay functions in programming allow for pausing code execution, giving deveÂlopers precise control over timing. These functions are essential for tasks such as content display, animations, synchronization, and managing asynchronous operations. In this article, we will discuss how can we create a d
3 min read
How to handle data fetching in React-Redux Applications ? Data fetching in React-Redux applications is a common requirement to retrieve data from APIs or other sources and use it within your components. This article explores various approaches to handling data fetching in React-Redux applications, providing examples and explanations for each approach.Table
4 min read