<?xml version="1.0" encoding="UTF-8"?><rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" > <channel> <title>aPI Archives - CopyCat Blog</title> <atom:link href="https://www.copycat.dev/blog/tag/api/feed/" rel="self" type="application/rss+xml" /> <link>https://www.copycat.dev/blog/tag/api/</link> <description>Perfect the art of copying code</description> <lastBuildDate>Tue, 07 Mar 2023 10:36:47 +0000</lastBuildDate> <language>en-US</language> <sy:updatePeriod> hourly </sy:updatePeriod> <sy:updateFrequency> 1 </sy:updateFrequency> <generator>https://wordpress.org/?v=6.7.1</generator> <image> <url>https://www.copycat.dev/blog/wp-content/uploads/2022/04/cropped-cat-4x-32x32.png</url> <title>aPI Archives - CopyCat Blog</title> <link>https://www.copycat.dev/blog/tag/api/</link> <width>32</width> <height>32</height> </image> <site xmlns="com-wordpress:feed-additions:1">213178576</site> <item> <title>Ultimate Guide to Fetching Data from API using React Fetch with Clear Examples</title> <link>https://www.copycat.dev/blog/react-fetch/?utm_source=rss&utm_medium=rss&utm_campaign=react-fetch</link> <comments>https://www.copycat.dev/blog/react-fetch/#respond</comments> <dc:creator><![CDATA[Emmanuel Uchenna]]></dc:creator> <pubDate>Wed, 20 Jul 2022 19:30:42 +0000</pubDate> <category><![CDATA[React.js]]></category> <category><![CDATA[aPI]]></category> <category><![CDATA[Fetching Data]]></category> <category><![CDATA[React]]></category> <category><![CDATA[React Fetch]]></category> <category><![CDATA[React Guide]]></category> <guid isPermaLink="false">https://www.copycat.dev/blog/?p=595</guid> <description><![CDATA[<p>Table of Contents Introduction to Fetching Data from APIWhat is a REST API: Fetching data from APIAdvantages of RESTFul APIs: Fetching data from APIFetching data from API in React SPAWhere Should you use the Fetch Method in React Application?Prerequisites to setup your CRAHow to use the Fetch API to fetch data in ReactHow to use the fetch() method […]</p> <p>The post <a rel="nofollow" href="https://www.copycat.dev/blog/react-fetch/">Ultimate Guide to Fetching Data from API using React Fetch with Clear Examples</a> appeared first on <a rel="nofollow" href="https://www.copycat.dev/blog">CopyCat Blog</a>.</p> ]]></description> <content:encoded><![CDATA[<div class="convertful-189269"></div> <figure class="wp-block-image"><a href="https://user-images.githubusercontent.com/24845008/179279697-cc1a44e9-efb7-4f9e-b10f-0423674f2598.png" target="_blank" rel="noreferrer noopener"><img decoding="async" src="https://user-images.githubusercontent.com/24845008/179279697-cc1a44e9-efb7-4f9e-b10f-0423674f2598.png" alt="react image"/></a></figure> <div id="rtoc-mokuji-wrapper" class="rtoc-mokuji-content frame3 preset2 animation-fade rtoc_open noto-sans" data-id="595" data-theme="CopyCat Theme"> <div id="rtoc-mokuji-title" class=" rtoc_left"> <button class="rtoc_open_close rtoc_open"></button> <span>Table of Contents</span> </div><ol class="rtoc-mokuji decimal_ol level-1"><li class="rtoc-item"><a href="#rtoc-1"><a href="https://gist.github.com/Eunit99/94f85423ab2912b6cc4608df3bcf133c#introduction-to-fetching-data-from-api"></a><strong>Introduction to Fetching Data from API</strong></a></li><li class="rtoc-item"><a href="#rtoc-2"><a href="https://gist.github.com/Eunit99/94f85423ab2912b6cc4608df3bcf133c#what-is-a-rest-api-fetching-data-from-api"></a><strong>What is a REST API: Fetching data from API</strong></a></li><li class="rtoc-item"><a href="#rtoc-3"><a href="https://gist.github.com/Eunit99/94f85423ab2912b6cc4608df3bcf133c#advantages-of-restful-apis-fetching-data-from-api"></a><strong>Advantages of RESTFul APIs: Fetching data from API</strong></a></li><li class="rtoc-item"><a href="#rtoc-4"><a href="https://gist.github.com/Eunit99/94f85423ab2912b6cc4608df3bcf133c#fetching-data-from-api-in-react-spa"></a><strong>Fetching data from API in React SPA</strong></a><ul class="rtoc-mokuji mokuji_ul level-2"><li class="rtoc-item"><a href="#rtoc-5"><strong>Where Should you use the Fetch Method in React Application?</strong></a></li></ul></li><li class="rtoc-item"><a href="#rtoc-6"><a href="https://gist.github.com/Eunit99/94f85423ab2912b6cc4608df3bcf133c#prerequisites-to-setup-your-cra"></a><strong>Prerequisites to setup your CRA</strong></a></li><li class="rtoc-item"><a href="#rtoc-7"><a href="https://gist.github.com/Eunit99/94f85423ab2912b6cc4608df3bcf133c#how-to-use-the-fetch-api-to-fetch-data-in-react"></a><strong>How to use the Fetch API to fetch data in React</strong></a><ul class="rtoc-mokuji mokuji_ul level-2"><li class="rtoc-item"><a href="#rtoc-8"><a href="https://gist.github.com/Eunit99/94f85423ab2912b6cc4608df3bcf133c#how-to-use-the-fetch-method-in-react-to-fetch-data-from-api"></a><strong>How to use the <code>fetch()</code> method in React to fetch data from API</strong></a></li></ul></li><li class="rtoc-item"><a href="#rtoc-9"><a href="https://gist.github.com/Eunit99/94f85423ab2912b6cc4608df3bcf133c#how-to-use-custom-react-hook-usefetch-to-fetch-data"></a><strong>How to use custom React hook (<code>useFetch</code>) to fetch data</strong></a></li><li class="rtoc-item"><a href="#rtoc-10"><a href="https://gist.github.com/Eunit99/94f85423ab2912b6cc4608df3bcf133c#steps-to-use-the-react-fetch-hook-library"></a><strong>Steps to use the <code>react-fetch-hook</code> library</strong></a><ul class="rtoc-mokuji mokuji_ul level-2"><li class="rtoc-item"><a href="#rtoc-11"><a href="https://gist.github.com/Eunit99/94f85423ab2912b6cc4608df3bcf133c#using-the-custom-react-hook-usefetch-to-fetch-data-from-api"></a><strong>Using the custom React hook (<code>useFetch</code>) to fetch data from API</strong></a></li></ul></li><li class="rtoc-item"><a href="#rtoc-12"><a href="https://gist.github.com/Eunit99/94f85423ab2912b6cc4608df3bcf133c#how-to-use-axios-to-fetch-data-from-api"></a><strong>How to use Axios to fetch data from API</strong></a></li><li class="rtoc-item"><a href="#rtoc-13"><a href="https://gist.github.com/Eunit99/94f85423ab2912b6cc4608df3bcf133c#steps-to-use-use-axios-to-fetch-data-from-api"></a><strong>Steps to use use Axios to fetch data from API</strong></a></li><li class="rtoc-item"><a href="#rtoc-14"><a href="https://gist.github.com/Eunit99/94f85423ab2912b6cc4608df3bcf133c#how-to-use-the-react-query-library-to-fetch-data-from-api"></a><strong>How to use the React Query to fetch data from API</strong></a></li><li class="rtoc-item"><a href="#rtoc-15"><a href="https://gist.github.com/Eunit99/94f85423ab2912b6cc4608df3bcf133c#steps-to-use-react-query-library-to-fetch-data-from-api"></a><strong>Steps to use React Query to fetch data from API</strong></a></li><li class="rtoc-item"><a href="#rtoc-16"><a href="https://gist.github.com/Eunit99/94f85423ab2912b6cc4608df3bcf133c#conclusion"></a><strong>Conclusion</strong></a></li><li class="rtoc-item"><a href="#rtoc-17"><a href="https://gist.github.com/Eunit99/94f85423ab2912b6cc4608df3bcf133c#videos-on-fetching-data-from-api-and-examples"></a><strong>Videos on Fetching Data from API and Examples</strong></a></li><li class="rtoc-item"><a href="#rtoc-18"><a href="https://gist.github.com/Eunit99/94f85423ab2912b6cc4608df3bcf133c#further-readings"></a><strong>Further readings</strong></a></li></ol></div><h2 id="rtoc-1" class="wp-block-heading"><a href="https://gist.github.com/Eunit99/94f85423ab2912b6cc4608df3bcf133c#introduction-to-fetching-data-from-api"></a><strong>Introduction to Fetching Data from API</strong></h2> <p>Often times, in fullstack web applications, you are required to either interact with a database; <em>this can be a relational or non-relational database</em>, or interact with an API. In such scenarios, you will need to send or request data through some network. Fetch allows you to send or get data across networks. As a React developer, you should be able to comfortably consume APIs in your React applications in order to build a full-fledged React application.</p> <h2 id="rtoc-2" class="wp-block-heading"><a href="https://gist.github.com/Eunit99/94f85423ab2912b6cc4608df3bcf133c#what-is-a-rest-api-fetching-data-from-api"></a><strong>What is a REST API: Fetching data from API</strong></h2> <p>A <a href="https://www.smashingmagazine.com/2018/01/understanding-using-rest-api/">REST API</a> is an API (<em>Application Programming Interface</em>) which allows two software programs to communicate with each other. An API outlines the proper way for a developer to write a program requesting services from an operating system or other application.</p> <p>REST stands for “Representational State Transfer” and it refers to an architectural style and approach to communication used in <a href="https://www.techtarget.com/searchapparchitecture/definition/Web-services">web services</a>. REST APIs follow a structure known as the <a href="https://gtjourney.gatech.edu/gt-devhub/documentation/restful-api-structure">REST Structure</a> for APIs. This consists of various rules that developers must follow when creating APIs.</p> <h2 id="rtoc-3" class="wp-block-heading"><a href="https://gist.github.com/Eunit99/94f85423ab2912b6cc4608df3bcf133c#advantages-of-restful-apis-fetching-data-from-api"></a><strong>Advantages of RESTFul APIs: Fetching data from API</strong></h2> <p>The RESTful API architecture is advantageous over other similar technologies such as SOAP (<em>Simple Object Access Protocol</em>) because REST uses less bandwidth, making it more suitable for efficient internet usage. REST API is universal to language or platform as such, it can be consumed with any language or ran on any platform. RESTful APIs can also be built with programming languages such as JavaScript or Python.</p> <h2 id="rtoc-4" class="wp-block-heading"><a href="https://gist.github.com/Eunit99/94f85423ab2912b6cc4608df3bcf133c#fetching-data-from-api-in-react-spa"></a><strong>Fetching data from API in React SPA</strong></h2> <p>There are several methods to use <a href="https://developer.mozilla.org/en-US/docs/Web/API">REST APIs</a> in a React application. These methods cut across using the built-in JavaScript <a href="https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API"><code>fetch()</code> API</a>, to using your own <a href="https://www.copycat.dev/blog/react-usestate-hook%ef%bf%bc/">custom React hook</a>, to using third party libraries such as <a href="https://www.educative.io/answers/what-is-axios">Axios</a>, which is used to make an HTTP request from Node.js or XMLHttpRequests right from the browser.</p> <p>When we make a data request from our application to an API, we must set up a <a href="https://www.copycat.dev/blog/react-usestate-hook%ef%bf%bc/">state</a> to store the data when it returns. Like Redux, a state is kept in a context object or a state management tool. But in order to keep things straightforward, we will store the returned data in the local state of React using <a href="https://www.copycat.dev/blog/author/copycat/">useState React hook</a>.</p> <p>The next step is to provide a state to manage the loading phase of your application in order to enhance the user experience and a second state to manage the error in the event that something goes wrong</p> <p>With that said, we therefore will have the following states:</p> <div class="wp-block-syntaxhighlighter-code "><pre class="brush: jscript; title: ; notranslate"> const [data, setData] = useState(null); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); </pre></div> <h3 id="rtoc-5" class="wp-block-heading"><strong>Where Should you use the Fetch Method in React Application?</strong></h3> <p>In your React application, you should <strong>always</strong> make your fetch request in the <a href="https://reactjs.org/docs/react-component.html#mounting"><code>componentDidMount</code></a> lifecycle method in a class component or using the <a href="https://reactjs.org/docs/hooks-intro.html"><code>useEffect hook</code></a> in a <a href="https://www.copycat.dev/blog/react-functional-components/">functional component</a>.</p> <p>This is due to the fact that when we fetch data from the backend, we perform an operation known as a side effect, which can result in a variety of outcomes for the same data fetching. The identical request can, for instance, return a success or an error. In React, we should avoid performing side effects directly within the component body to avoid inconsistencies.</p> <p>In this case, we will fetch our data in the Hook like so:</p> <div class="wp-block-group"><div class="wp-block-group__inner-container is-layout-flow wp-block-group-is-layout-flow"> <div class="wp-block-group"><div class="wp-block-group__inner-container is-layout-flow wp-block-group-is-layout-flow"><div class="wp-block-syntaxhighlighter-code "><pre class="brush: jscript; title: ; notranslate"> componentDidMount() { fetch(`https://api.github.com/users/eunit99/repos`) .then(res => res.json()) .then( (result) => { this.setState({ isLoaded: true, items: result.items }); }, // Note: it's important to handle errors here // instead of a catch() block so that we don't swallow // exceptions from actual bugs in components. (error) => { this.setState({ isLoaded: true, error }); } ) } </pre></div> <div class="wp-block-syntaxhighlighter-code "><pre class="brush: jscript; title: ; notranslate"> // Note: the empty deps array [] means // this useEffect will run once // similar to componentDidMount() useEffect(() => { fetch(`https://api.github.com/users/eunit99/repos`) .then(res => res.json()) .then( (result) => { setIsLoaded(true); setItems(result); }, // Note: it's important to handle errors here // instead of a catch() block so that we don't swallow // exceptions from actual bugs in components. (error) => { setIsLoaded(true); setError(error); } ) }, []) </pre></div></div></div> </div></div> <p>A sample API response may look like so:</p> <div class="wp-block-syntaxhighlighter-code "><pre class="brush: jscript; title: ; notranslate"> { "id": 350135946, "node_id": "MDEwOlJlcG9zaXRvcnkzNTAxMzU5NDY=", "name": "advance-loan", "full_name": "Eunit99/advance-loan", "private": false, "owner": { "login": "Eunit99", "id": 24845008, "node_id": "MDQ6VXNlcjI0ODQ1MDA4", "avatar_url": "https://avatars.githubusercontent.com/u/24845008?v=4", "gravatar_id": "", "url": "https://api.github.com/users/Eunit99", "html_url": "https://github.com/Eunit99", "followers_url": "https://api.github.com/users/Eunit99/followers", "following_url": "https://api.github.com/users/Eunit99/following{/other_user}", "gists_url": "https://api.github.com/users/Eunit99/gists{/gist_id}", "starred_url": "https://api.github.com/users/Eunit99/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/Eunit99/subscriptions", "organizations_url": "https://api.github.com/users/Eunit99/orgs", "repos_url": "https://api.github.com/users/Eunit99/repos", "events_url": "https://api.github.com/users/Eunit99/events{/privacy}", "received_events_url": "https://api.github.com/users/Eunit99/received_events", "type": "User", "site_admin": false }, "html_url": "https://github.com/Eunit99/advance-loan", "description": null, "fork": false, "url": "https://api.github.com/repos/Eunit99/advance-loan", "forks_url": "https://api.github.com/repos/Eunit99/advance-loan/forks", "keys_url": "https://api.github.com/repos/Eunit99/advance-loan/keys{/key_id}", "collaborators_url": "https://api.github.com/repos/Eunit99/advance-loan/collaborators{/collaborator}", "teams_url": "https://api.github.com/repos/Eunit99/advance-loan/teams", "hooks_url": "https://api.github.com/repos/Eunit99/advance-loan/hooks", "issue_events_url": "https://api.github.com/repos/Eunit99/advance-loan/issues/events{/number}", "events_url": "https://api.github.com/repos/Eunit99/advance-loan/events", "assignees_url": "https://api.github.com/repos/Eunit99/advance-loan/assignees{/user}", "branches_url": "https://api.github.com/repos/Eunit99/advance-loan/branches{/branch}", "tags_url": "https://api.github.com/repos/Eunit99/advance-loan/tags", "blobs_url": "https://api.github.com/repos/Eunit99/advance-loan/git/blobs{/sha}", "git_tags_url": "https://api.github.com/repos/Eunit99/advance-loan/git/tags{/sha}", "git_refs_url": "https://api.github.com/repos/Eunit99/advance-loan/git/refs{/sha}", "trees_url": "https://api.github.com/repos/Eunit99/advance-loan/git/trees{/sha}", "statuses_url": "https://api.github.com/repos/Eunit99/advance-loan/statuses/{sha}", "languages_url": "https://api.github.com/repos/Eunit99/advance-loan/languages", "stargazers_url": "https://api.github.com/repos/Eunit99/advance-loan/stargazers", "contributors_url": "https://api.github.com/repos/Eunit99/advance-loan/contributors", "subscribers_url": "https://api.github.com/repos/Eunit99/advance-loan/subscribers", "subscription_url": "https://api.github.com/repos/Eunit99/advance-loan/subscription", "commits_url": "https://api.github.com/repos/Eunit99/advance-loan/commits{/sha}", "git_commits_url": "https://api.github.com/repos/Eunit99/advance-loan/git/commits{/sha}", "comments_url": "https://api.github.com/repos/Eunit99/advance-loan/comments{/number}", "issue_comment_url": "https://api.github.com/repos/Eunit99/advance-loan/issues/comments{/number}", "contents_url": "https://api.github.com/repos/Eunit99/advance-loan/contents/{+path}", "compare_url": "https://api.github.com/repos/Eunit99/advance-loan/compare/{base}...{head}", "merges_url": "https://api.github.com/repos/Eunit99/advance-loan/merges", "archive_url": "https://api.github.com/repos/Eunit99/advance-loan/{archive_format}{/ref}", "downloads_url": "https://api.github.com/repos/Eunit99/advance-loan/downloads", "issues_url": "https://api.github.com/repos/Eunit99/advance-loan/issues{/number}", "pulls_url": "https://api.github.com/repos/Eunit99/advance-loan/pulls{/number}", "milestones_url": "https://api.github.com/repos/Eunit99/advance-loan/milestones{/number}", "notifications_url": "https://api.github.com/repos/Eunit99/advance-loan/notifications{?since,all,participating}", "labels_url": "https://api.github.com/repos/Eunit99/advance-loan/labels{/name}", "releases_url": "https://api.github.com/repos/Eunit99/advance-loan/releases{/id}", "deployments_url": "https://api.github.com/repos/Eunit99/advance-loan/deployments", "created_at": "2021-03-21T22:29:30Z", "updated_at": "2021-09-03T01:11:41Z", "pushed_at": "2021-04-17T07:58:20Z", "git_url": "git://github.com/Eunit99/advance-loan.git", "ssh_url": "git@github.com:Eunit99/advance-loan.git", "clone_url": "https://github.com/Eunit99/advance-loan.git", "svn_url": "https://github.com/Eunit99/advance-loan", "homepage": null, "size": 25511, "stargazers_count": 1, "watchers_count": 1, "language": "JavaScript", "has_issues": true, "has_projects": true, "has_downloads": true, "has_wiki": true, "has_pages": false, "forks_count": 0, "mirror_url": null, "archived": false, "disabled": false, "open_issues_count": 0, "license": null, "allow_forking": true, "is_template": false, "web_commit_signoff_required": false, "topics": [], "visibility": "public", "forks": 0, "open_issues": 0, "watchers": 1, "default_branch": "main" } </pre></div> <p>The sample response above is from the GitHub REST API when I make a GET request to the following endpoint <a href="https://api.github.com/users/eunit99">https://api.github.com/users/eunit99</a>. It returns all the stored data about a user called <code>eunit99</code>. With this response, we can decide to render it whichever way we like in our React app.</p> <h2 id="rtoc-6" class="wp-block-heading"><a href="https://gist.github.com/Eunit99/94f85423ab2912b6cc4608df3bcf133c#prerequisites-to-setup-your-cra"></a><strong>Prerequisites to setup your CRA</strong></h2> <p>Before you proceed with this tutorial, you must satisfy the following conditions:</p> <ol class="wp-block-list"> <li><a href="https://nodejs.org/">Node.js ≥v6</a> is installed on your local machine</li> <li><a href="https://www.npmjs.com/">NPM</a> is installed on your local machine</li> <li>You have an understanding of <a href="https://reactjs.org/docs/create-a-new-react-app.html">React.js</a></li> <li>You have an understanding of <a href="https://www.freecodecamp.org/news/introduction-to-react-hooks/">React hooks</a></li> </ol> <p>In this guide, I shall walk you through how to fetch data from REST APIs in your React application using the following methodologies:</p> <ul class="wp-block-list"> <li>Fetch API</li> <li>custom React hook (<code>useFetch</code>)</li> <li><a href="https://github.com/axios/axios">Axios</a></li> <li><a href="https://www.copycat.dev/blog/react-query/">React Query</a> Library</li> <li>Async/Await</li> </ul> <p>I will walk you through setting your React application to implementing all of the methods outlined above.</p> <p>Let us jump right in <img src="https://s.w.org/images/core/emoji/15.0.3/72x72/1f387.png" alt="🎇" class="wp-smiley" style="height: 1em; max-height: 1em;" /><img src="https://s.w.org/images/core/emoji/15.0.3/72x72/1f386.png" alt="🎆" class="wp-smiley" style="height: 1em; max-height: 1em;" /><img src="https://s.w.org/images/core/emoji/15.0.3/72x72/1f389.png" alt="🎉" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p> <figure class="wp-block-image"><a href="https://user-images.githubusercontent.com/24845008/174059296-102441b6-1a97-4e57-871d-69247fba5ee9.gif" target="_blank" rel="noreferrer noopener"><img decoding="async" src="https://user-images.githubusercontent.com/24845008/174059296-102441b6-1a97-4e57-871d-69247fba5ee9.gif" alt="dancing panda"/></a></figure> <h2 id="rtoc-7" class="wp-block-heading"><a href="https://gist.github.com/Eunit99/94f85423ab2912b6cc4608df3bcf133c#how-to-use-the-fetch-api-to-fetch-data-in-react"></a><strong>How to use the Fetch API to fetch data in React</strong></h2> <p>The <a href="https://developer.mozilla.org/en-US/docs/Web/API/Fetch_APIhttps://developer.mozilla.org/en-US/docs/Web/API/Fetch_API"><code>fetch()</code> API</a> (Fetch API) is an in-built JavaScript method which provides a better interface for accessing and manipulating parts of the HTTP pipeline, such as requests and responses. Fetch API provides an easy to use way to fetch resources asynchronously across the network.</p> <p>The Fetch API method can be basic as in the case below and making a request can really be simple to set up. However, The <code>fetch()</code> method always takes in a <strong>compulsory argument</strong>, which is the <code>path</code> or <code>URL</code> to the resource or API you want to fetch from and an optional parameter, like so:</p> <pre class="wp-block-preformatted">fetch(url, options)</pre> <p>The <code>options</code> parameters allow you to specify the type of operation you want to carry out using <code>HTTP</code> methods like the <code>GET</code> method to request data from an endpoint, <code>POST</code> to send data to an endpoint, <code>PUT</code> to update data in an endpoint, or even <code>DELETE</code> to remove data from an endpoint.</p> <p>A basic fetch request may look like so:</p> <div class="wp-block-syntaxhighlighter-code "><pre class="brush: jscript; title: ; notranslate"> fetch('https://api.github.com/users/eunit99/repos') .then(response => response.json()) .then(data => console.log(data)); </pre></div> <h3 id="rtoc-8" class="wp-block-heading"><a href="https://gist.github.com/Eunit99/94f85423ab2912b6cc4608df3bcf133c#how-to-use-the-fetch-method-in-react-to-fetch-data-from-api"></a><strong>How to use the <code>fetch()</code> method in React to fetch data from API</strong></h3> <p>In this section, I shall walk you through how to use the <code>fetch()</code> method in your React app using React <a href="https://www.copycat.dev/blog/react-functional-components/">functional component</a>. To get started, set up your React application using the below commands:</p> <pre class="wp-block-preformatted">mkdir dev && cd dev && npx create-react-app rest-apis-tutorial && cd rest-apis-tutorial && npm start</pre> <p>What the commands above do are:</p> <ul class="wp-block-list"> <li>Creates a new directory called <code>dev</code></li> <li>Change directory into <code>dev</code></li> <li>Create a new React app called <code>rest-apis-tutorial</code> using the CRA command</li> <li>Change directory into <code>rest-apis-tutorial</code></li> <li>Start your React app using <code>npm start</code></li> </ul> <p>You should get the following in your terminal upon completion of the commands above:</p> <div class="wp-block-syntaxhighlighter-code "><pre class="brush: jscript; title: ; notranslate"> Compiled successfully! You can now view rest-apis-tutorial in the browser. Local: http://localhost:3000 On Your Network: http://192.168.137.1:3000 Note that the development build is not optimized. To create a production build, use npm run build. webpack compiled successfully </pre></div> <p>Your React app will then start hot reloading your development environment and your app should be running on <code>localhost:3000</code> by default.</p> <figure class="wp-block-image"><a href="https://user-images.githubusercontent.com/24845008/176993096-b0464d20-5db0-4da2-b67a-cef27bbcaa3e.png" target="_blank" rel="noreferrer noopener"><img decoding="async" src="https://user-images.githubusercontent.com/24845008/176993096-b0464d20-5db0-4da2-b67a-cef27bbcaa3e.png" alt="image of React app"/></a></figure> <p><strong>NOTE:</strong> We will make use of this app <code>rest-apis-tutorial</code> throughout this tutorial.</p> <h4 class="wp-block-heading"><a href="https://gist.github.com/Eunit99/94f85423ab2912b6cc4608df3bcf133c#using-the-fetch-method-to-fetch-from-an-api"></a><strong>Using the <code>fetch</code> method to fetch from an API</strong></h4> <p>In your <code>App.js</code> file, paste the following code:</p> <div class="wp-block-syntaxhighlighter-code "><pre class="brush: jscript; title: ; notranslate"> import { useState, useEffect } from "react"; export default function App() { const [data, setData] = useState(null); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); useEffect(() => { fetch(`https://api.github.com/users/eunit99/repos`) .then(response => response.json()) .then((usefulData) => { console.log(usefulData); setLoading(false); setData(usefulData); }) .catch((e) => { console.error(`An error occurred: ${e}`) }); }, []); return ( <> <div className="App"> {loading && <p>Loading...</p>} {!loading && <p>Fetched data</p>} </div> </> ) } </pre></div> <p>In your console, you should have a response similar to this as a JSON response, which shows a list of repositories using from the endpoint <code>https://api.github.com/users/eunit99/repos</code>.</p> <figure class="wp-block-image"><a href="https://user-images.githubusercontent.com/24845008/178941103-9f1b76eb-42e0-49c6-b5cd-e13f70c5a431.png" target="_blank" rel="noreferrer noopener"><img decoding="async" src="https://user-images.githubusercontent.com/24845008/178941103-9f1b76eb-42e0-49c6-b5cd-e13f70c5a431.png" alt="using the Fetch API to fetch"/></a></figure> <figure class="wp-block-image"><a href="https://camo.githubusercontent.com/92834313af14004ef79df566a60d6d3cd06b99bdd07a3ec4fff31b2de80cd8a2/68747470733a2f2f632e74656e6f722e636f6d2f6f7a64515350576e6b644941414141432f7468696e6b696e672d7461702e676966" target="_blank" rel="noreferrer noopener"><img decoding="async" src="https://camo.githubusercontent.com/92834313af14004ef79df566a60d6d3cd06b99bdd07a3ec4fff31b2de80cd8a2/68747470733a2f2f632e74656e6f722e636f6d2f6f7a64515350576e6b644941414141432f7468696e6b696e672d7461702e676966" alt="thinking gif"/></a></figure> <p>You might be wondering what each piece of code is doing?</p> <p>In the code above, you used the <code>fetch()</code> method to request data from the resource endpoint (<code>https://api.github.com/users/eunit99/repos</code>) as seen inside the useEffect Hook. This operation returns a promise that could either resolve or reject. If it resolves, you handle the response using <code>.then()</code> block. However, it is important to note that at this stage, the returned data is a Response object, which is not the actual format that we need, although it is useful to check for the HTTP status and to handle errors. If the request fails, we use the <code>.catch</code> blog to handle the exception.</p> <h2 id="rtoc-9" class="wp-block-heading"><a href="https://gist.github.com/Eunit99/94f85423ab2912b6cc4608df3bcf133c#how-to-use-custom-react-hook-usefetch-to-fetch-data"></a><strong>How to use custom React hook (<code>useFetch</code>) to fetch data</strong></h2> <p>Since the introduction of hooks in React 16.8, you have the ability to use state and other React features without writing a class. In addition to this, React hook paved the way for developers like you to write their own custom hooks; thereby reducing repetition, spaghetti code, and helping you keep to software development best practices such as the <a href="https://www.digitalocean.com/community/tutorials/what-is-dry-development#:~:text=DRY%2C%20which%20stands%20for%20'don,of%20abstractions%20and%20avoiding%20redundancy.">DRY principle</a>.</p> <p>You may find that writing the useEffect hook and all of its boilerplate within each component where you want to fetch data becomes tiresome and time-consuming over time.</p> <p>You can utilize a custom hook as a specific abstraction, which you can develop yourself from a third-party library, to reduce the amount of code you reuse (like you will be walked through, using the library <code>react-fetch-hook</code>).</p> <p>Finally, you can greatly reduce the size of your components by using a custom hook to create your HTTP request. All you need to do is call the hook at the component’s top.</p> <h2 id="rtoc-10" class="wp-block-heading"><a href="https://gist.github.com/Eunit99/94f85423ab2912b6cc4608df3bcf133c#steps-to-use-the-react-fetch-hook-library"></a><strong>Steps to use the <code>react-fetch-hook</code> library</strong></h2> <ul class="wp-block-list"> <li>Install the library in your React application:npm i react-fetch-hook</li> <li>Import the <code>useFetch</code> hook at the top in <code>App.js</code> like so:import useFetch from “react-fetch-hook”;</li> </ul> <h3 id="rtoc-11" class="wp-block-heading"><a href="https://gist.github.com/Eunit99/94f85423ab2912b6cc4608df3bcf133c#using-the-custom-react-hook-usefetch-to-fetch-data-from-api"></a><strong>Using the custom React hook (<code>useFetch</code>) to fetch data from API</strong></h3> <p>In your <code>App.js</code> file, paste the following code:</p> <div class="wp-block-syntaxhighlighter-code "><pre class="brush: jscript; title: ; notranslate"> import useFetch from "react-fetch-hook"; export default function App() { const { isLoading, data, error } = useFetch("https://api.github.com/users/eunit99/repos"); if (error) { return ( <div> <p>Code: ${error.status}</p> <p>Message: ${error.statusText}</p> </div> ) } if (!isLoading) { console.log(data); } return ( <> <div className="App"> {isLoading && <p>Loading...</p>} {!isLoading && <p>Fetched data</p>} </div> </> ) } </pre></div> <p>In your console, you should have a response similar to this as a JSON response, which shows a list of repositories using from the endpoint <code>https://api.github.com/users/eunit99/repos</code>.</p> <figure class="wp-block-image"><a href="https://user-images.githubusercontent.com/24845008/178941103-9f1b76eb-42e0-49c6-b5cd-e13f70c5a431.png" target="_blank" rel="noreferrer noopener"><img decoding="async" src="https://user-images.githubusercontent.com/24845008/178941103-9f1b76eb-42e0-49c6-b5cd-e13f70c5a431.png" alt="using the Fetch API to fetch"/></a></figure> <h2 id="rtoc-12" class="wp-block-heading"><a href="https://gist.github.com/Eunit99/94f85423ab2912b6cc4608df3bcf133c#how-to-use-axios-to-fetch-data-from-api"></a><strong>How to use Axios to fetch data from API</strong></h2> <p>Another approach to making requests with React is to use the library <a href="https://axios-http.com/docs/intro">Axios</a> which is a promise-based HTTP client for the browser and Node.js. Since Axios is promise-based, you benefit from async and await for asynchronous code that is easier to read. You can intercept and cancel requests using Axios, and it also contains a built-in function that offers client-side security against cross-site request forgery.</p> <p>We will simply update our Fetch implementation in this example by first installing <a href="https://axios-http.com/docs/intro">Axios</a> using npm:</p> <h2 id="rtoc-13" class="wp-block-heading"><a href="https://gist.github.com/Eunit99/94f85423ab2912b6cc4608df3bcf133c#steps-to-use-use-axios-to-fetch-data-from-api"></a><strong>Steps to use use Axios to fetch data from API</strong></h2> <ul class="wp-block-list"> <li>Install the library in your React application: with either <code>Yarn</code> or <code>NPM</code>:npm install axiosoryarn add axios</li> <li>Import the <code>axios</code> library at the top in <code>App.js</code> like so:import axios from “axios”;</li> </ul> <p>What axios enables us to do is to use the exact same promise syntax as fetch – but instead of using our first then callback to manually determine whether the response is okay and throw an error, axios takes care of that for us.</p> <div class="wp-block-syntaxhighlighter-code "><pre class="brush: jscript; title: ; notranslate"> import { useState, useEffect } from "react"; import axios from "axios"; export default function App() { const [data, setData] = useState(null); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); useEffect(() => { const getData = async () => { try { const response = await axios.get( `https://api.github.com/users/eunit99/repos` ); setData(response.data); setError(null); console.log(data); } catch (err) { setError(err.message); setData(null); } finally { setLoading(false); } }; getData(); }, [loading]); return ( <> <div className="App"> {loading && <p>Loading...</p>} {!loading && <p>Fetched data</p>} </div> </> ) } </pre></div> <p>In your console, you should have a response similar to this as a JSON response, which shows a list of repositories using from the endpoint <code>https://api.github.com/users/eunit99/repos</code>.</p> <figure class="wp-block-image"><a href="https://user-images.githubusercontent.com/24845008/178941103-9f1b76eb-42e0-49c6-b5cd-e13f70c5a431.png" target="_blank" rel="noreferrer noopener"><img decoding="async" src="https://user-images.githubusercontent.com/24845008/178941103-9f1b76eb-42e0-49c6-b5cd-e13f70c5a431.png" alt="using the Fetch API to fetch"/></a></figure> <h2 id="rtoc-14" class="wp-block-heading"><a href="https://gist.github.com/Eunit99/94f85423ab2912b6cc4608df3bcf133c#how-to-use-the-react-query-library-to-fetch-data-from-api"></a><strong>How to use the React Query to fetch data from API</strong></h2> <p>We can accomplish a lot more with the <a href="https://www.copycat.dev/blog/react-query/">React Query</a> module than merely get data. By eliminating errors and making our program feel faster, it offers support for caching and refetching, which has an impact on the entire user experience.</p> <p><a href="https://www.copycat.dev/blog/react-query/">React Query</a> offers a custom Hook that we can reuse to fetch data throughout our app, similar to the first approach. Install the library before before using it:</p> <h2 id="rtoc-15" class="wp-block-heading"><a href="https://gist.github.com/Eunit99/94f85423ab2912b6cc4608df3bcf133c#steps-to-use-react-query-library-to-fetch-data-from-api"></a><strong>Steps to use React Query to fetch data from API</strong></h2> <ul class="wp-block-list"> <li>Install the library in your React application:npm i react-query</li> <li>Import the <a href="https://www.copycat.dev/blog/react-query/">React Query</a> library at the top in <code>index.js</code> like so:</li> </ul> <div class="wp-block-syntaxhighlighter-code "><pre class="brush: jscript; title: ; notranslate"> import { QueryClient, QueryClientProvider } from "react-query"; const queryClient = new QueryClient(); </pre></div> <ul class="wp-block-list"> <li>The client instance must then be passed to the <code>QueryClientProvider</code> we imported from <code>react-query</code> to wrap our parent component. Consequently, your <code>index.js</code> should look like so:</li> </ul> <div class="wp-block-syntaxhighlighter-code "><pre class="brush: jscript; title: ; notranslate"> import React from 'react'; import ReactDOM from 'react-dom/client'; import './index.css'; import App from './App'; import { QueryClient, QueryClientProvider } from "react-query"; const queryClient = new QueryClient(); const root = ReactDOM.createRoot(document.getElementById('root')); root.render( <QueryClientProvider client={queryClient}> <App /> </QueryClientProvider> ); </pre></div> <ul class="wp-block-list"> <li>The next step is to fetch data using the <code>useQuery</code> Hook method from <code>react-query</code>, passing a distinct query key and the function that the query uses to do so:</li> </ul> <div class="wp-block-syntaxhighlighter-code "><pre class="brush: jscript; title: ; notranslate"> import axios from "axios"; import { useQuery } from "react-query"; export default function App() { const { isLoading, error, data } = useQuery("posts", () => axios(`https://api.github.com/users/eunit99/repos`) ); console.log(data); return ( <> <div className="App"> {isLoading && <p>Loading...</p>} {!isLoading && <p>Fetched data</p>} </div> </> ); } </pre></div> <p>In your console, you should have a response similar to this as a JSON response, which shows a list of repositories using from the endpoint <code>https://api.github.com/users/eunit99/repos</code>.</p> <figure class="wp-block-image"><a href="https://user-images.githubusercontent.com/24845008/178941103-9f1b76eb-42e0-49c6-b5cd-e13f70c5a431.png" target="_blank" rel="noreferrer noopener"><img decoding="async" src="https://user-images.githubusercontent.com/24845008/178941103-9f1b76eb-42e0-49c6-b5cd-e13f70c5a431.png" alt="using the Fetch API to fetch"/></a></figure> <figure class="wp-block-image"><a href="https://user-images.githubusercontent.com/24845008/175513672-2c6d6341-06d4-4cd6-8923-d1cba4e7adb4.png" target="_blank" rel="noreferrer noopener"><img decoding="async" src="https://user-images.githubusercontent.com/24845008/175513672-2c6d6341-06d4-4cd6-8923-d1cba4e7adb4.png" alt="glass"/></a></figure> <h2 id="rtoc-16" class="wp-block-heading"><a href="https://gist.github.com/Eunit99/94f85423ab2912b6cc4608df3bcf133c#conclusion"></a><strong>Conclusion</strong></h2> <p>Almost all of the information you require about data fetching methods is covered in this tutorial. You were walked through how to retrieve data from a REST API.</p> <p>You were also shown how to control various states, such as the loading and error stages. Now, you should now feel more at ease pulling data into your React application.</p> <p>Try to spread this guide on the internet if you find it interesting.</p> <figure class="wp-block-image"><a href="https://camo.githubusercontent.com/2136fa1e022b7637a4014cbb9f338b5761f9ac84dd985d10d9d1241f24fae467/68747470733a2f2f6d65646961312e67697068792e636f6d2f6d656469612f656c79336170696a3336424a686f5a3233342f323030772e776562703f6369643d656366303565343763696773746f3567676d63786772397273366a6179637035366a36767162776e64697a6965786778267269643d323030772e776562702663743d67" target="_blank" rel="noreferrer noopener"><img decoding="async" src="https://camo.githubusercontent.com/2136fa1e022b7637a4014cbb9f338b5761f9ac84dd985d10d9d1241f24fae467/68747470733a2f2f6d65646961312e67697068792e636f6d2f6d656469612f656c79336170696a3336424a686f5a3233342f323030772e776562703f6369643d656366303565343763696773746f3567676d63786772397273366a6179637035366a36767162776e64697a6965786778267269643d323030772e776562702663743d67" alt="Congratulations"/></a></figure> <p>Thinking of learning more? Find below some link to further tutorials:</p> <figure class="wp-block-image"><a href="https://camo.githubusercontent.com/e0e50473279b59ef4cf77d4a913159888022ee5d0ceae8c4b36d4a538fc34ede/68747470733a2f2f632e74656e6f722e636f6d2f64705f685142475430724941414141432f7468696e6b2d736d6172742e676966" target="_blank" rel="noreferrer noopener"><img decoding="async" src="https://camo.githubusercontent.com/e0e50473279b59ef4cf77d4a913159888022ee5d0ceae8c4b36d4a538fc34ede/68747470733a2f2f632e74656e6f722e636f6d2f64705f685142475430724941414141432f7468696e6b2d736d6172742e676966" alt="thinking gif"/></a></figure> <h2 id="rtoc-17" class="wp-block-heading"><a href="https://gist.github.com/Eunit99/94f85423ab2912b6cc4608df3bcf133c#videos-on-fetching-data-from-api-and-examples"></a><strong>Videos on Fetching Data from API and Examples</strong></h2> <figure class="wp-block-image"><a href="https://www.youtube.com/watch?v=djCuFrLLjVk"><img decoding="async" src="https://user-images.githubusercontent.com/24845008/177755082-b595a654-23ec-458c-a71b-4a911a9ebb20.png" alt="Fetch API Explained - Working with Data & APIs in JavaScript"/></a></figure> <figure class="wp-block-image"><a href="https://user-images.githubusercontent.com/24845008/177755560-47df006f-27da-4fb5-8472-8464dea1bbad.png" target="_blank" rel="noreferrer noopener"><img decoding="async" src="https://user-images.githubusercontent.com/24845008/177755560-47df006f-27da-4fb5-8472-8464dea1bbad.png" alt="JavaScript Fetch API || Fetch data from API and display data into browser."/></a></figure> <h2 id="rtoc-18" class="wp-block-heading"><a href="https://gist.github.com/Eunit99/94f85423ab2912b6cc4608df3bcf133c#further-readings"></a><strong>Further readings</strong></h2> <ul class="wp-block-list"> <li><a href="https://gtjourney.gatech.edu/gt-devhub/documentation/restful-api-structure">REST API Structure</a></li> <li><a href="https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API">Fetch API by Mozilla Developer Network</a></li> <li><a href="https://www.copycat.dev/blog/react-useref">React UseRef: Create Scalable Apps That Perform Like a Dream</a></li> <li><a href="https://www.copycat.dev/blog/react-best-practices/">React Best Practices 2021 – Featuring 20+ Experts</a> </li> <li><a href="https://www.copycat.dev/blog/react-usestate-hook%ef%bf%bc/">How to use the React useState Hook</a></li> <li><a href="https://www.copycat.dev/blog/react-usestate-hook">Why and How to Use React useState Hook</a></li> </ul> <p>You can build UI faster than your competition with <a href="https://www.copycat.dev/">CopyCat</a>. Just copy production-ready code generated directly from Figma designs using AI. As a result, you can focus on building interactions, animations, networking and everything else that will make you stand out. You can be an exceptional front end or react developer who develops UI quickly using CopyCat.</p> <p><em>We know what it’s like to do redundant work.</em> Our goal is to help you avoid development rework that leads to delivery delays. Let us help you find efficient ways to write quality code.</p> <p>You’ll be 2X faster at developing UI. You’ll meet your deadlines and spend your time solving exciting challenges, too! Best of all, you’ll eliminate sprint delays and design inconsistencies.</p> <div class="wp-block-buttons is-content-justification-center is-layout-flex wp-container-core-buttons-is-layout-1 wp-block-buttons-is-layout-flex"> <div class="wp-block-button"><a class="wp-block-button__link has-background wp-element-button" href="https://www.copycat.dev/" style="background-color:#7b3beb">START BUILDING FASTER</a></div> </div> <p>The post <a rel="nofollow" href="https://www.copycat.dev/blog/react-fetch/">Ultimate Guide to Fetching Data from API using React Fetch with Clear Examples</a> appeared first on <a rel="nofollow" href="https://www.copycat.dev/blog">CopyCat Blog</a>.</p> ]]></content:encoded> <wfw:commentRss>https://www.copycat.dev/blog/react-fetch/feed/</wfw:commentRss> <slash:comments>0</slash:comments> <post-id xmlns="com-wordpress:feed-additions:1">595</post-id> </item> </channel> </rss>