In this article, you will learn how to use the Axios library in React.
Let's look at everything using the example of requests to the server, display the received data in a table, pass the load check component, and all this using React Hooks.
What is Axios?
Axios is one of the most popular HTTP clients for browsers and promises-based node.js.
Axios has support for requests, receiving responses from the server, transforming them, and automatically converting them to JSON.
Before we start, let's create a new React project:
npx create-react-app react-axios-table
Let's go into it:
cd react-axios-table
Project data
We will use an array of objects as data for our project:
[
{
id: 101,
firstName: 'Sue',
lastName: 'Corson',
email: 'DWhalley@in.gov',
phone: '(612)211-6296',
address: {
streetAddress: '9792 Mattis Ct',
city: 'Waukesha',
state: 'WI',
zip: '22178'
},
description: 'et lacus magna dolor...',
}
]
Link to data
Configuring a component to work with Axios
Load the Axios library:
npm i axios
We import axios into the component from which we will send requests to the server:
import axios from 'axios'
Because in the project we use React Hooks, import useState and useEffect (read more about hooks in the react here ):
import React, { useEffect, useState } from 'react';
Next, add the following code to the component:
function App() {
const [appState, setAppState] = useState();
useEffect(() => {
const apiUrl = 'http://www.filltext.com/?rows=32&id={number|1000}&firstName={firstName}&lastName={lastName}&email={email}&phone={phone|(xxx)xxx-xx-xx}&address={addressObject}&description={lorem|32}';
axios.get(apiUrl).then((resp) => {
const allPersons = resp.data;
setAppState(allPersons);
});
}, [setAppState]);
return (
<div className="app">
</div>
);
}
export default App;
Let's take a closer look at the code:
const [appState, setAppState] = useState();
Responsible for the state of the state in the component:
useEffect(() => {}, [setAppState])
useEffect will watch for changes in setAppState and re-render if needed
const apiUrl=''
we substitute our link here
axios.get(apiUrl).then((resp) => {
const allPersons = resp.data;
setAppState(allPersons);
});
send a get request to the server, then save the received JSON data to the state
Download check component
Create a components folder in src . In it, create the UserData.js component and add the following code:
function UserData(props) {
const { persons } = props
if (!persons || persons.length === 0) return <p> .</p>
return (
<div>
<table>
<thead>
<tr>
<th>id</th>
<th>firstName</th>
<th>lastName</th>
<th>email</th>
<th>phone</th>
</tr>
</thead>
<tbody>
{
persons.map((person) =>
<tr key={person.id}>
<td>{person.id}</td>
<td>{person.firstName}</td>
<td>{person.lastName}</td>
<td>{person.email}</td>
<td>{person.phone}</td>
</tr>
)
}
</tbody>
</table>
</div>
)
}
export default UserData
We will transfer data received from the server to the props of the component.
if (!persons || persons.length === 0) return <p> .</p>
check if there is data from the server
{
persons.map((person) =>
<tr key={person.id}>
<td>{person.id}</td>
<td>{person.firstName}</td>
<td>{person.lastName}</td>
<td>{person.email}</td>
<td>{person.phone}</td>
</tr>
)
}
Using the map method, we go through the array with people, create a string for each person. Don't forget about key .
In the components folder, create LoadingPersonsData.js and paste the following code:
function OnLoadingUserData(Component) {
return function LoadingPersonsData({ isLoading, ...props }) {
if (!isLoading) return <Component {...props} />
else return (
<div>
<h1>, !</h1>
</div>
)
}
}
export default LoadingPersonsData
The code above is a higher-order component in React. It takes another component as props and then returns some logic. In our case, the component checks isLoading . While the data is loading, we display the loading message, as soon as isLoading is false, we return the component with the data.
Let's make changes to our App.js to be able to check data loading. Let's
import our components into App.js :
import UserData from './components/UserData'
import OnLoadingUserData from './components/OnLoadingUserData'
Add the following code:
function App() {
const DataLoading = LoadingPersonsData(UserData);
const [appState, setAppState] = useState(
{
loading: false,
persons: null,
}
)
useEffect(() => {
setAppState({loading: true})
const apiUrl = 'http://www.filltext.com/?rows=32&id={number|1000}&firstName={firstName}&lastName={lastName}&email={email}&phone={phone|(xxx)xxx-xx-xx}&address={addressObject}&description={lorem|32}';
axios.get(apiUrl).then((resp) => {
const allPersons = resp.data;
setAppState({
loading: false,
persons: allPersons
});
});
}, [setAppState]);
return (
<div className="app">
<DataLoading isLoading={appState.loading} persons={appState.persons} />
</div>
);
}
export default App;
const DataLoading = LoadingPersonsData(UserData);
We create a new component, equate it to our higher-order component and wrap a UserData (data display component) with it.
We add a new property loading: false to the state , by which we will determine the loading of data from the server.
<DataLoading isLoading={appState.loading} persons={appState.persons} />
Render the component and pass the props to our higher-order component.
Let's add some css and when loading the data, we will see the following window:
And now, when the get request to the server is completed successfully, the data is received:
Now we know how to use Axios get with the REST API.
If you have any questions or suggestions, leave them in the comments. I will be glad to answer.