How to fetch data from APIs using Asynchronous await in ReactJS ?
In this article, we are going to make an API request to any APIs that you want using ReactJS, and fetch data using Asynchronous await. Here we are using something called Axios which is a library in ReactJS.
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.
const Value = await promise;
Creating React Application And Installing Module:
Step 1: Create a React application using the following command:
npx create-react-app foldername
Step 2: After creating your project folder i.e foldername, move to it using the following command:
Step 3: After creating the ReactJS application, Install the required module using the following command:
npm install axios
Project Structure: It will look like the following.
Note: As an example, we would use the API https://jsonplaceholder.typicode.com/posts/ which would give us random data. Here our goal is to see what is presented in this data. You can replace it with your API and make changes in the div App. If we run https://jsonplaceholder.typicode.com/posts/ API on postman, it will show data in JSON format as shown below:
Step to Run Application: Run the application using the following command from the root directory of the project:
Output: Now open your browser and go to http://localhost:3000/, you will see the following output: