React and Axios: A Beginner's Guide to API Calls
This tutorial will teach you how to use Axios to get data, then how to manipulate it and finally display it on your page through filtering. Along the way you'll learn how to use mapping, filters, and include methods. Most importantly, you will create a simple loader to handle the loading status of data obtained from the API endpoint.
1. Setup Project
Let’s set up a React project using the create-react-app
command in the terminal:
npx create-react-app project-name
Then, open the project directory through a terminal window and enter npm install axios
to install Axios locally for the project.
2.Select target API
We will use the Random User Generator API to get random user information to use in our application.
Let's add the Axios module to our application by importing it into our App.js
file.
import axios from 'axios'
The Random User Generator API provides a range of options for creating various types of data. You can check out the documentation for more information, but for this tutorial we'll keep it simple.
We want to get ten different users, we just need the first name, last name, and unique ID, which is what React needs when creating the list of elements. Also, to make the call more specific, let's take the nationality option as an example.
Here is the API URL we will call:
https://randomuser.me/api/?results=10&inc=name,registered&nat=fr
Please note that I did not use the id
option provided in the API as it sometimes returns null
for some users. Therefore, to ensure that each user has a unique value, I included the registered
option in the API.
You can copy and paste this into your browser and you will see the data returned in JSON format.
Now, the next step is to make the API call through Axios.
3. Create application state
First, let's create a state using the useState
hook in React so that we can store the fetched data.
In our App
component, import the useState
hook from React and create the state as shown below.
import React, { useState } from "react"; import axios from "axios"; const App = () => { const [users, setUsers] = useState([]); const [store, setStore] = useState([]); return ( <div> </div> ); }; export default App;
Here you can see the users
and store
status. One will be used for filtering purposes and will not be edited, the other will hold the filtered results that will be displayed in the DOM.
4.Use axios to obtain data
The next thing we need to do is create a getUsers
function to handle the acquisition of data. In this function, we use axios
to get the data from the API using the get
method.
Now, in order to display the data we fetched when the page loads, we will import a React hook named useEffect
and call the getUsers
function in it.
useEffect
The hook basically manages side effects in functional components and is similar to the componentDidMount()
lifecycle hook used in React class-based components. This hook accepts an empty array as second argument for side effect cleanup.
Update the code in the App
component as shown below so that we can inspect the response data in the console.
import React, { useState, useEffect } from "react"; const App = () => { const [users, setUsers] = useState([]); const [store, setStore] = useState([]); const getUsers = () => { axios.get("https://randomuser.me/api/?results=10&inc=name,registered&nat=fr") .then(response => console.log(response)) }; useEffect(() => { getUsers(); }, []); return ( <div> </div> ); }; export default App;
When you check the console you will see an object output. If you open this object, there is another object inside, named data
, and inside data, there is an array named results
.
If we want to return a specific value from the result, we can update the axios.get
call as follows:
axios.get("https://randomuser.me/api/?results=10&inc=name,registered&nat=fr") .then(response => console.log(response.data.results[0].name.first))
Here we record the name of the first value in the result array.
5.Processing result data
Now let’s use JavaScript’s built-in map
method to iterate over each element in the array and create a new array of JavaScript objects with a new structure.
Update your getUsers
function with the following code:
const getUsers = () => { axios .get("https://randomuser.me/api/?results=10&inc=name,registered&nat=fr") .then((response) => { const newData = response.data.results.map((result) => ({ name: `${result.name.first} ${result.name.last}`, id: result.registered })); setUsers(newData); setStore(newData); }) .catch((error) => { console.log(error); }); };
In the above code, we created a variable named newData
. It stores the results of viewing the response.data.results
array using the map
method. In the map
callback, we reference each element of the array as a result
(note the singular/plural difference). Additionally, by using the key-value pairs for each object in the array, we create another object using the name
and id
key-value pairs.
一般情况下,在浏览器中查看API调用结果,会看到里面有first
和last
键值对name
对象,但没有全名的键值对。因此,从上面的代码中,我们能够组合 first
和 last
名称,在新的 JavaScript 对象中创建全名。请注意,JSON 和 JavaScript 对象是不同的东西,尽管它们的工作方式基本相同。
然后我们将新的中间数据设置为 setUsers
和 setStore
状态。
6. 通过过滤填充数据存储
过滤的想法非常简单。我们有我们的 store
状态,它始终保持原始数据不变。然后,通过在该状态上使用 filter
函数,我们只获取匹配的元素,然后将它们分配给 users
状态。
const filteredData = store.filter((item) => ( item.name.toLowerCase().includes(event.target.value.toLowerCase()))
filter
方法需要一个函数作为参数,该函数针对数组中的每个元素运行。这里我们将数组中的每个元素称为 item
。然后,我们获取每个 item
的 name
键并将其转换为小写,以使我们的过滤功能不区分大小写。
获得 item
的 name
键后,我们检查该键是否包含我们输入的搜索字符串。 includes
是另一个内置 JavaScript 方法。我们将在输入字段中键入的搜索字符串作为参数传递给 includes
,如果该字符串包含在调用它的变量中,则它会返回。同样,我们将输入字符串转换为小写,这样无论您输入大写还是小写输入都无关紧要。
最后,filter
方法返回匹配的元素。因此,我们只需将这些元素存储在 setUsers
状态中即可。
使用我们创建的函数的最终版本更新 App
组件。
const filterNames = (event) => { const filteredData = store.filter((item) => item.name.toLowerCase().includes(event.target.value.toLowerCase()) ); setUsers(filteredData); };
7. 创建组件
尽管对于这个小示例,我们可以将所有内容放入 App
组件中,但让我们利用 React 并制作一些小型功能组件。
让我们向应用程序添加几个组件。首先,我们从单独的 JavaScript 文件导入组件(我们将很快定义这些文件):
import Lists from "./components/Lists"; import SearchBar from "./components/SearchBar";
接下来,我们更新应用程序组件的 return
语句以使用这些组件:
return ( <div className="Card"> <div className="header">NAME LIST</div> <SearchBar searchFunction={filterNames} /> <Lists usernames={users} /> </div> );
目前,我们将只关注功能。稍后我将提供我创建的 CSS 文件。
请注意,我们有 searchFunction
属性用于 SearchBar
组件,以及 usernames
属性用于 Lists
组件.
另请注意,我们使用 users
状态而不是 store
状态来显示数据,因为 users
状态包含已过滤的数据结果。
SearchBar
组件
这个组件非常简单。它仅将 filterNames
函数作为 prop,并在输入字段更改时调用该函数。将以下代码放入 components/SearchBar.js 中:
import React from 'react'; const SearchBar = ({ searchFunction}) => { return ( <div> <input className="searchBar" type='search' onChange={searchFunction} /> </div> ) }; export default SearchBar;
列表组件
该组件将简单地列出用户的姓名。这位于 components/List.js 中:
import React from 'react'; const Lists = ({ usernames }) => { return ( <div> <ul> {usernames.map(username => ( <li key={username.id}>{username.name}</li> ))} </ul> </div> ) }; export default Lists;
在这里,我们再次使用 map
方法来获取数组中的每个项目,并从中创建一个 <li>
项目。请注意,当您使用 map
创建项目列表时,您需要使用 key
以便 React 跟踪每个列表项目。
8.跟踪加载状态
让我们使用 useState
挂钩创建一个加载状态,以显示何时尚未获取数据。
const [loading, setLoading] = useState(false);
接下来,我们将更新数据获取方法中的加载状态。
const getUsers = () => { axios.get("https://randomuser.me/api/?results=10&inc=name,registered&nat=fr") .then((response) => { const newData = response.data.results.map((result) => ({ name: `${result.name.first} ${result.name.first}`, id: result.registered, })); setLoading(true); setUsers(newData); setStore(newData); }) .catch((error) => { console.log(error); }); };
在这里,我们创建了一个 loading
状态并将其初始设置为 false。然后我们在使用 setLoading
状态获取数据时将此状态设置为 true。
最后,我们将更新 return 语句以呈现加载状态。
return ( <> {loading ? ( <div className="Card"> <div className="header">NAME LIST</div> <SearchBar searchFunction={filterNames} /> <Lists users={users} /> </div> ) : ( <div className="loader"></div> )} </> );
使用 JavaScript 三元运算符,我们在加载状态为 false 时有条件地渲染 SearchBar
和 Lists
组件,然后在加载状态为 true 时渲染加载程序。另外,我们创建了一个简单的加载器来在界面中显示加载状态。
9. 添加一些 CSS 进行样式设置
您可以在下面找到特定于此示例的 CSS 文件。
body, html { -webkit-font-smoothing: antialiased; margin: 0; padding: 0; font-family: "Raleway", sans-serif; -webkit-text-size-adjust: 100%; } body { display: flex; justify-content: center; font-size: 1rem/16; margin-top: 50px; } li, ul { list-style: none; margin: 0; padding: 0; } ul { margin-top: 10px; } li { font-size: 0.8rem; margin-bottom: 8px; text-align: center; color: #959595; } li:last-of-type { margin-bottom: 50px; } .Card { font-size: 1.5rem; font-weight: bold; display: flex; flex-direction: column; align-items: center; width: 200px; border-radius: 10px; background-color: white; box-shadow: 0 5px 3px 0 #ebebeb; } .header { position: relative; font-size: 20px; margin: 12px 0; color: #575757; } .header::after { content: ""; position: absolute; left: -50%; bottom: -10px; width: 200%; height: 1px; background-color: #f1f1f1; } .searchBar { text-align: center; margin: 5px 0; border: 1px solid #c4c4c4; height: 20px; color: #575757; border-radius: 3px; } .searchBar:focus { outline-width: 0; } .searchBar::placeholder { color: #dadada; } .loader { border: 15px solid #ccc; border-top: 15px solid #add8e6; border-bottom: 15px solid #add8e6; border-radius: 50%; width: 80px; height: 80px; animation: rotate 2s linear infinite; } @keyframes rotate { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }
结论
在本教程中,我们使用随机用户生成器 API 作为随机数据源。然后,我们从 API 端点获取数据,并使用 map
方法在新的 JavaScript 对象中重构结果。
接下来是使用 filter
和 includes
方法创建过滤函数。最后,我们创建了两个不同的组件,并在尚未获取数据时有条件地以加载状态渲染我们的组件。
在过去的几年里,React 越来越受欢迎。事实上,我们在 Envato Market 中有许多项目可供购买、审查、实施等。如果您正在寻找有关 React 的其他资源,请随时查看它们。
The above is the detailed content of React and Axios: A Beginner's Guide to API Calls. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











Blogs are the ideal platform for people to express their opinions, opinions and opinions online. Many newbies are eager to build their own website but are hesitant to worry about technical barriers or cost issues. However, as the platform continues to evolve to meet the capabilities and needs of beginners, it is now starting to become easier than ever. This article will guide you step by step how to build a WordPress blog, from theme selection to using plugins to improve security and performance, helping you create your own website easily. Choose a blog topic and direction Before purchasing a domain name or registering a host, it is best to identify the topics you plan to cover. Personal websites can revolve around travel, cooking, product reviews, music or any hobby that sparks your interests. Focusing on areas you are truly interested in can encourage continuous writing

There are four ways to adjust the WordPress article list: use theme options, use plugins (such as Post Types Order, WP Post List, Boxy Stuff), use code (add settings in the functions.php file), or modify the WordPress database directly.

Recently, we showed you how to create a personalized experience for users by allowing users to save their favorite posts in a personalized library. You can take personalized results to another level by using their names in some places (i.e., welcome screens). Fortunately, WordPress makes it very easy to get information about logged in users. In this article, we will show you how to retrieve information related to the currently logged in user. We will use the get_currentuserinfo(); function. This can be used anywhere in the theme (header, footer, sidebar, page template, etc.). In order for it to work, the user must be logged in. So we need to use

Do you want to know how to display child categories on the parent category archive page? When you customize a classification archive page, you may need to do this to make it more useful to your visitors. In this article, we will show you how to easily display child categories on the parent category archive page. Why do subcategories appear on parent category archive page? By displaying all child categories on the parent category archive page, you can make them less generic and more useful to visitors. For example, if you run a WordPress blog about books and have a taxonomy called "Theme", you can add sub-taxonomy such as "novel", "non-fiction" so that your readers can

In the past, we have shared how to use the PostExpirator plugin to expire posts in WordPress. Well, when creating the activity list website, we found this plugin to be very useful. We can easily delete expired activity lists. Secondly, thanks to this plugin, it is also very easy to sort posts by post expiration date. In this article, we will show you how to sort posts by post expiration date in WordPress. Updated code to reflect changes in the plugin to change the custom field name. Thanks Tajim for letting us know in the comments. In our specific project, we use events as custom post types. Now

Are you looking for ways to automate your WordPress website and social media accounts? With automation, you will be able to automatically share your WordPress blog posts or updates on Facebook, Twitter, LinkedIn, Instagram and more. In this article, we will show you how to easily automate WordPress and social media using IFTTT, Zapier, and Uncanny Automator. Why Automate WordPress and Social Media? Automate your WordPre

One of our users asked other websites how to display the number of queries and page loading time in the footer. You often see this in the footer of your website, and it may display something like: "64 queries in 1.248 seconds". In this article, we will show you how to display the number of queries and page loading time in WordPress. Just paste the following code anywhere you like in the theme file (e.g. footer.php). queriesin

To build a website using WordPress hosting, you need to: select a reliable hosting provider. Buy a domain name. Set up a WordPress hosting account. Select a topic. Add pages and articles. Install the plug-in. Customize your website. Publish your website.
