
{"id":15692,"date":"2022-12-19T11:29:43","date_gmt":"2022-12-19T05:59:43","guid":{"rendered":"https:\/\/www.guvi.in\/blog\/?p=15692"},"modified":"2023-11-22T13:52:28","modified_gmt":"2023-11-22T08:22:28","slug":"how-to-fetch-data-using-api-in-react","status":"publish","type":"post","link":"https:\/\/guviv3.codingpuppet.com\/blog\/how-to-fetch-data-using-api-in-react\/","title":{"rendered":"Use ReactJS to Fetch and Display Data from API &#8211; 5 Simple Steps"},"content":{"rendered":"\n<p>In this blog, we\u2019ll learn <strong>how to fetch and display data from APIs and use it in a ReactJS app.<\/strong> There are multiple ways to fetch data in a React application, and we\u2019ll walk you through those methods. With the help of APIs, we can fetch the data from servers and display it in our application. Let&#8217;s first understand what an API is.<\/p>\n\n\n\n<p><strong>API <\/strong>stands for <strong>&#8220;Application Programming Interface&#8221;,<\/strong> which is a method of communication between different applications. <strong>ReactJS <\/strong>is an open-source JavaScript-based library developed by Facebook used to create web applications&#8217; user interfaces. As ReactJS is dynamic in nature, we can get the data using APIs and display it in our application.<\/p>\n\n\n\n<p>To render some data in our front end, we either need a backend to store our data and then make use of the data, or we can simply use APIs to have some mock data while building an application.<\/p>\n\n\n\n<p>When we use APIs, we don\u2019t need a backend and are also not required to build anything from scratch. Mostly, we use the REST API or the GraphQL API to access the data added to the server. Before we get into depth, we should understand how an API works.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>How does an API work<\/strong>?<\/h2>\n\n\n\n<p>The workings of an API are very easy to understand. Here&#8217;s an example, say we want to build a new application but don\u2019t have our own backend. Now, to display the news in our application, we need some third-party APIs to access their backend server and display the data in our app.<\/p>\n\n\n\n<p>Now, there are three things we must have noted<strong>: an application, a server, and an API. <\/strong>Most times, the <em>API is in between the app and server because whenever the client requests the data, the API makes a GET request to the server and sends that back to the application for display.<\/em><\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Methods to Fetch and Display Data from API<\/strong>:<\/h2>\n\n\n\n<p>We commonly use a Web API called REST, or <strong>REpresentational State Transfer API<\/strong>, which consists of HTTP methods to fetch data from the server and display it in the application. A REST API has several methods, which are discussed further below:<\/p>\n\n\n\n<ol>\n<li><strong>GET: <\/strong>This method is used to fetch data from a server endpoint.<\/li>\n\n\n\n<li><strong>POST: <\/strong>This method is used to post the data to a server endpoint.<\/li>\n\n\n\n<li><strong>DELETE: <\/strong>This method is used to delete the data from a server endpoint.<\/li>\n\n\n\n<li><strong>PUT: <\/strong>This method is used to update or modify the data from a server endpoint.<\/li>\n<\/ol>\n\n\n\n<p>Now as you have understood all the methods of the API, we can now move on to how the data is fetched from the server. To fetch the data, we use the <strong>GET <\/strong>method.<\/p>\n\n\n\n<p><em>The different ways of Fetching the data in a React application are given below:<\/em><\/p>\n\n\n\n<ul>\n<li>Using React Hooks<\/li>\n\n\n\n<li>Using JavaScript Fetch API<\/li>\n\n\n\n<li>Using async\/await<\/li>\n\n\n\n<li>Using Axios library<\/li>\n\n\n\n<li>Using React query<\/li>\n<\/ul>\n\n\n\n<p>For now, we\u2019ll only discuss the two ways of fetching data i.e., using <strong>JavaScript Fetch API <\/strong>and using <strong>Axios library API<\/strong>.<\/p>\n\n\n\n<p><strong>Here are the <a href=\"https:\/\/www.guvi.in\/blog\/prerequisites-for-reactjs\/\" target=\"_blank\" rel=\"noopener\">6 Essential Prerequisites For Learning ReactJS<\/a> you must know in order to be proficient in ReactJS.<\/strong><\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Using JavaScript Fetch API<\/h2>\n\n\n\n<p>The JavaScript Fetch API is an inbuilt browser\u2019s native API that gives an easy interface to fetch the data from the network. The simplest way to use fetch() is by taking one argument and the path from where the data is to be fetched and then returning a promise in a JSON object.<\/p>\n\n\n\n<p>In this example, we are going to use mock data provided freely by <a href=\"https:\/\/jsonplaceholder.typicode.com\/\" target=\"_blank\" rel=\"noopener\">JSONplaceholder<\/a> in JSON format. We are going to use the user&#8217;s endpoint from that API i.e., <a href=\"https:\/\/jsonplaceholder.typicode.com\/users\" target=\"_blank\" rel=\"noopener\">https:\/\/jsonplaceholder.typicode.com\/users<\/a>.<\/p>\n\n\n\n<p><strong>See the below steps to implement and use Fetch API to fetch the data in a react app.<\/strong><\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Step 1. Create a React Application<\/strong><\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>npx create-react-app demo<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Step 2. Change your Project Directory<\/strong><\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>cd demo<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Step 3. Access the API Endpoint<\/strong><\/h3>\n\n\n\n<p>Now, as done in the above method 1, where we\u2019ll also access the API endpoint and store it in a const variable so that we can use it anytime and anywhere.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>const url = \u201chttps:\/\/jsonplaceholder.typicode.com\/users\u201d;<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Step 4. Import the useState() Hook and Set it to Hold Data<\/strong><\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>import React, { useState } from 'react';\n\nconst &#91;data, setData] = useState(&#91;])<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Step 5. Create a FetchInfo() Callback Function to Fetch and Store Data<\/strong><\/h3>\n\n\n\n<p>We will create a callback function that will store the user&#8217;s data and then use the useEffect() hook to make the function run every time the page loads.&nbsp;Now we get the data from the API using the fetch() method in the data variable.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>const fetchInfo = () =&gt; { \nreturn fetch(url) \n        .then((res) =&gt; res.json()) \n        .then((d) =&gt; setData(d)) \n}\n\nuseEffect(() =&gt; {\n\tfetchInfo();\n}, &#91;])<\/code><\/pre>\n\n\n\n<p>Now your App.js file should look like the below:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import \".\/App.css\";\nimport React, { useState, useEffect } from \"react\";\n\nfunction App() {\n  const url = \"https:\/\/jsonplaceholder.typicode.com\/users\";\n  const &#91;data, setData] = useState(&#91;]);\n\n  const fetchInfo = () =&gt; {\n    return fetch(url)\n      .then((res) =&gt; res.json())\n      .then((d) =&gt; setData(d))\n  }\n\n\n  useEffect(() =&gt; {\n    fetchInfo();\n  }, &#91;]);\n\n  return (\n    &lt;div className=\"App\"&gt;\n      &lt;h1 style={{ color: \"green\" }}&gt;using JavaScript inbuilt FETCH API&lt;\/h1&gt;\n      &lt;center&gt;\n        {data.map((dataObj, index) =&gt; {\n          return (\n            &lt;div\n              style={{\n                width: \"15em\",\n                backgroundColor: \"#35D841\",\n                padding: 2,\n                borderRadius: 10,\n                marginBlock: 10,\n              }}\n            &gt;\n              &lt;p style={{ fontSize: 20, color: 'white' }}&gt;{dataObj.name}&lt;\/p&gt;\n            &lt;\/div&gt;\n          );\n        })}\n      &lt;\/center&gt;\n    &lt;\/div&gt;\n  );\n}\n\nexport default App;<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Output<\/strong><\/h3>\n\n\n\n<p><strong>The output for the above example is as follows:<\/strong><\/p>\n\n\n\n<figure class=\"wp-block-image size-full\"><img decoding=\"async\" loading=\"lazy\" width=\"1194\" height=\"946\" src=\"https:\/\/www.guvi.in\/blog\/wp-content\/uploads\/2022\/12\/r1.png\" alt=\"React Fetch API\" class=\"wp-image-15699\" srcset=\"https:\/\/guviv3.codingpuppet.com\/blog\/wp-content\/uploads\/2022\/12\/r1.png 1194w, https:\/\/guviv3.codingpuppet.com\/blog\/wp-content\/uploads\/2022\/12\/r1-300x238.png 300w, https:\/\/guviv3.codingpuppet.com\/blog\/wp-content\/uploads\/2022\/12\/r1-768x608.png 768w, https:\/\/guviv3.codingpuppet.com\/blog\/wp-content\/uploads\/2022\/12\/r1-150x119.png 150w\" sizes=\"(max-width: 1194px) 100vw, 1194px\" \/><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Using Axios Library<\/strong><\/h2>\n\n\n\n<p><strong>Axios is an online HTTP library running on node.js that allows us to make various HTTP requests to a given server endpoint.<\/strong> If we see it working, then it uses the <em>http <\/em>module on the server side, whereas it uses <em>XMLHttpRequests on the<\/em> browser side. For this example, we are going to use the GET method to fetch and display the data in our React application. Here we don\u2019t need to convert the result into a JSON object; it already comes as a JSON object.<\/p>\n\n\n\n<p>See the below steps for the installation of the Axios library and the fetching process of the data in a react app.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Step 1. Create a React Application<\/strong><\/h3>\n\n\n\n<p>The first thing to do is create a React application from scratch using the below <strong>npx command.<\/strong> Write or copy\/paste the following to create a react app in your desired directory and name the project of your choice. For this example, we have created a project called &#8220;demo.&#8221;<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>npx create-react-app demo<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Step 2. Change your Project Directory<\/strong><\/h3>\n\n\n\n<p>Once the project is created, change the directory to where the app folder is created.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>cd demo<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Step 3. Install the Axios Library with npm or yarn<\/strong><\/h3>\n\n\n\n<p>For using the axios library, we need to install that and we can do that using two ways i.e, either install using NPM or Yarn. Install it with any one of your choice or requirements.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>npm install axios<\/code><\/pre>\n\n\n\n<p>Or<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>yarn add axios<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Step 4. Access the API Endpoint<\/strong><\/h3>\n\n\n\n<p>Now, as done in the above method 1, where we\u2019ll also access the API endpoint and store it in a const variable so that we can use it anytime and anywhere.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>const url = \u201chttps:\/\/jsonplaceholder.typicode.com\/users\u201d;<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Step 5. Import the Axios and useState() Hook and Set it to Hold Data<\/strong><\/h3>\n\n\n\n<p>Import the installed axios library to the App.js file and also the useState() hook to&nbsp;hold the data in a variable.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import React, { useState } from 'react';\nimport axios from 'axios';\n\nconst &#91;data, setData] = useState(&#91;])<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Step 6. Create a FetchInfo() Callback Function to Fetch and Store Data<\/strong><\/h3>\n\n\n\n<p>In this method also, we will create a callback function that will store the user&#8217;s data and then use the useEffect() hook to make the function run every time the page loads.&nbsp;<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>const fetchInfo = () =&gt; { \n  return axios.get(url) \n           .then((response) =&gt; setUser(response.data));\n}\n\nuseEffect(() =&gt; { \n      fetchInfo(); \n}, &#91;])<\/code><\/pre>\n\n\n\n<p>Now your App.js file should look like below:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import \".\/App.css\";\nimport React, { useState, useEffect } from \"react\";\nimport axios from \"axios\";\n\nfunction App() {\n  const url = \"https:\/\/jsonplaceholder.typicode.com\/users\";\n  const &#91;data, setData] = useState(&#91;]);\n\n  const fetchInfo = () =&gt; {\n    return axios.get(url).then((res) =&gt; setData(res.data));\n  };\n\n  useEffect(() =&gt; {\n    fetchInfo();\n  }, &#91;]);\n\n  return (\n    &lt;div className=\"App\"&gt;\n      &lt;h1 style={{ color: \"green\" }}&gt;using Axios Library to Fetch Data&lt;\/h1&gt;\n      &lt;center&gt;\n        {data.map((dataObj, index) =&gt; {\n          return (\n            &lt;div\n              style={{\n                width: \"15em\",\n                backgroundColor: \"#CD8FFD\",\n                padding: 2,\n                borderRadius: 10,\n                marginBlock: 10,\n              }}\n            &gt;\n              &lt;p style={{ fontSize: 20, color: 'white' }}&gt;{dataObj.name}&lt;\/p&gt;\n            &lt;\/div&gt;\n          );\n        })}\n      &lt;\/center&gt;\n    &lt;\/div&gt;\n  );\n}\n\nexport default App;<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Output<\/strong>:<\/h3>\n\n\n\n<p><strong>The output for the above example is as follows:<\/strong><\/p>\n\n\n\n<figure class=\"wp-block-image size-full\"><img decoding=\"async\" loading=\"lazy\" width=\"1194\" height=\"950\" src=\"https:\/\/www.guvi.in\/blog\/wp-content\/uploads\/2022\/12\/r2.png\" alt=\"React Axios library\" class=\"wp-image-15700\" srcset=\"https:\/\/guviv3.codingpuppet.com\/blog\/wp-content\/uploads\/2022\/12\/r2.png 1194w, https:\/\/guviv3.codingpuppet.com\/blog\/wp-content\/uploads\/2022\/12\/r2-300x239.png 300w, https:\/\/guviv3.codingpuppet.com\/blog\/wp-content\/uploads\/2022\/12\/r2-768x611.png 768w, https:\/\/guviv3.codingpuppet.com\/blog\/wp-content\/uploads\/2022\/12\/r2-150x119.png 150w\" sizes=\"(max-width: 1194px) 100vw, 1194px\" \/><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\">Summing Up<\/h2>\n\n\n\n<p>In this blog, we learned <strong>how to fetch data using an API in a React.js application<\/strong>. We hope you get a very good understanding of how an API works, how to fetch data from an API, and the different ways of fetching data using an API. Additionally, we learned how to use the inbuilt JavaScript Fetch API to fetch data and also saw how to use the Axios library, which is a better alternative to the inbuilt Fetch API.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">FAQs<\/h2>\n\n\n<div id=\"rank-math-faq\" class=\"rank-math-block\">\n<div class=\"rank-math-list \">\n<div id=\"faq-question-1691999166508\" class=\"rank-math-list-item\">\n<h3 class=\"rank-math-question \">Q1. How to fetch data from API and display in JS?<\/h3>\n<div class=\"rank-math-answer \">\n\n<p><strong>Ans<\/strong>.To fetch data from an API and display it in JS, you need to <strong>define a const data and store it in JSON by await response. json() method. <\/strong>When we get the data from API by fetch() method in the data variable; pass it to the function which will show the data fetched.<\/p>\n\n<\/div>\n<\/div>\n<div id=\"faq-question-1692000906837\" class=\"rank-math-list-item\">\n<h3 class=\"rank-math-question \">Q2. How to display and extract JSON data from an API?<\/h3>\n<div class=\"rank-math-answer \">\n\n<p><strong>Ans<\/strong>. To get JSON from a REST API endpoint, you must\u00a0<strong>send an HTTP GET request to the REST API server and provide an Accept: application\/json request header<\/strong>. The Accept: application\/json header tells the REST API server that the API client expects to receive data in JSON format.<\/p>\n\n<\/div>\n<\/div>\n<div id=\"faq-question-1692000927543\" class=\"rank-math-list-item\">\n<h3 class=\"rank-math-question \">Q3. What is a fetch API in JavaScript?<\/h3>\n<div class=\"rank-math-answer \">\n\n<p><strong>Ans<\/strong>. The Fetch API is\u00a0<strong>a modern interface that allows you to make HTTP requests to servers from web browsers<\/strong>. If you have worked with XMLHttpRequest (XHR) object, the Fetch API can perform all the tasks as the XHR object does. In addition, the Fetch API is much simpler and cleaner.<\/p>\n\n<\/div>\n<\/div>\n<\/div>\n<\/div>","protected":false},"excerpt":{"rendered":"<p>In this blog, we\u2019ll learn how to fetch and display data from APIs and use it in a ReactJS app. There are multiple ways to fetch data in a React application, and we\u2019ll walk you through those methods. With the help of APIs, we can fetch the data from servers and display it in our [&hellip;]<\/p>\n","protected":false},"author":15,"featured_media":15718,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[737],"tags":[],"views":"49791","authorinfo":{"name":"Tarun Singh","url":"https:\/\/guviv3.codingpuppet.com\/blog\/author\/tarun\/"},"thumbnailURL":"https:\/\/guviv3.codingpuppet.com\/blog\/wp-content\/uploads\/2022\/12\/Fetch-Data-using-API-in-React.Js-300x169.png","jetpack_featured_media_url":"https:\/\/guviv3.codingpuppet.com\/blog\/wp-content\/uploads\/2022\/12\/Fetch-Data-using-API-in-React.Js.png","_links":{"self":[{"href":"https:\/\/guviv3.codingpuppet.com\/blog\/wp-json\/wp\/v2\/posts\/15692"}],"collection":[{"href":"https:\/\/guviv3.codingpuppet.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/guviv3.codingpuppet.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/guviv3.codingpuppet.com\/blog\/wp-json\/wp\/v2\/users\/15"}],"replies":[{"embeddable":true,"href":"https:\/\/guviv3.codingpuppet.com\/blog\/wp-json\/wp\/v2\/comments?post=15692"}],"version-history":[{"count":37,"href":"https:\/\/guviv3.codingpuppet.com\/blog\/wp-json\/wp\/v2\/posts\/15692\/revisions"}],"predecessor-version":[{"id":33254,"href":"https:\/\/guviv3.codingpuppet.com\/blog\/wp-json\/wp\/v2\/posts\/15692\/revisions\/33254"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/guviv3.codingpuppet.com\/blog\/wp-json\/wp\/v2\/media\/15718"}],"wp:attachment":[{"href":"https:\/\/guviv3.codingpuppet.com\/blog\/wp-json\/wp\/v2\/media?parent=15692"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/guviv3.codingpuppet.com\/blog\/wp-json\/wp\/v2\/categories?post=15692"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/guviv3.codingpuppet.com\/blog\/wp-json\/wp\/v2\/tags?post=15692"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}