Axios is a popular JavaScript library used to make HTTP requests from React Native applications. It can be used to communicate with REST APIs and backend servers.
With Axios, you can perform common operations such as GET, POST, PUT and DELETE requests.
React Native App
↓
Axios
↓
REST API
↓
Server
↓
JSON Data
↓
React Native App
Axios is a Promise-based HTTP client that can be used to send requests to web servers and APIs.
A React Native application can use Axios to retrieve or send data to a backend server.
axios.get(url);
Axios provides a convenient way to work with HTTP requests.
Axios needs to be installed in the React Native project.
npm install axios
After installation, Axios can be imported into JavaScript or TypeScript files.
Import Axios before using it.
import axios from "axios";
You can now use Axios methods such as axios.get() and
axios.post().
The get() method is used to retrieve data.
axios.get(
"https://example.com/api/users"
)
.then(response => {
console.log(response.data);
});
Axios provides the response data through response.data.
Axios works well with async and await.
async function loadUsers() {
const response =
await axios.get(
"https://example.com/api/users"
);
console.log(response.data);
}
This style can make asynchronous API code easier to read.
Axios returns a response object containing information about the request and server response.
const response =
await axios.get(url);
console.log(response.data);
console.log(response.status);
console.log(response.headers);
The data property is commonly used to access the returned
API data.
API data can be stored in React state.
const [users, setUsers] =
useState([]);
async function loadUsers() {
const response =
await axios.get(url);
setUsers(response.data);
}
Axios can be used inside useEffect() when data should be
loaded when a screen starts.
useEffect(() => {
loadUsers();
}, []);
The function can request data and update the component state.
import React, {
useEffect,
useState
} from "react";
import axios from "axios";
function UsersScreen() {
const [users, setUsers] =
useState([]);
async function loadUsers() {
const response =
await axios.get(
"https://example.com/api/users"
);
setUsers(response.data);
}
useEffect(() => {
loadUsers();
}, []);
}
The post() method is used to send data to a server.
axios.post(
"https://example.com/api/users",
{
name: "Rahul",
email: "rahul@example.com"
}
);
The second argument contains the request body.
async function createUser() {
const response =
await axios.post(
"https://example.com/api/users",
{
name: "Rahul",
email: "rahul@example.com"
}
);
console.log(response.data);
}
The put() method can be used to update existing data.
axios.put(
"https://example.com/api/users/10",
{
name: "Rahul Kumar"
}
);
The exact behavior depends on how the backend API implements PUT.
The patch() method is commonly used when only part of a
resource needs to be updated.
axios.patch(
"https://example.com/api/users/10",
{
name: "Rahul Kumar"
}
);
The delete() method is used to request deletion of a
resource.
axios.delete(
"https://example.com/api/users/10"
);
The server determines whether the requested deletion is permitted.
Use try...catch to handle errors when using Axios with
async and await.
try {
const response =
await axios.get(url);
console.log(response.data);
} catch (error) {
console.log(error);
}
An error message can be stored in state.
const [error, setError] =
useState("");
try {
const response =
await axios.get(url);
setUsers(response.data);
} catch (error) {
setError(
"Unable to load users"
);
}
A loading state can indicate that an Axios request is currently running.
const [loading, setLoading] =
useState(true);
async function loadUsers() {
try {
setLoading(true);
const response =
await axios.get(url);
setUsers(response.data);
} finally {
setLoading(false);
}
}
The ActivityIndicator component can be displayed while Axios is loading data.
{loading ? (
<ActivityIndicator />
) : (
<Text>
Data Loaded
</Text>
)}
Axios allows you to send HTTP headers with a request.
axios.get(url, {
headers: {
"Content-Type":
"application/json"
}
});
Headers can contain information required by an API.
axios.post(
url,
{
name: "Rahul"
},
{
headers: {
"Content-Type":
"application/json"
}
}
);
The third argument can contain Axios request configuration.
Axios can be used to send login credentials to a backend API.
async function login() {
const response =
await axios.post(
"https://example.com/api/login",
{
email: email,
password: password
}
);
console.log(response.data);
}
The server can validate the credentials and return an authentication response.
An education application can use Axios to load courses from an API.
async function loadCourses() {
try {
const response =
await axios.get(
"https://example.com/api/courses"
);
setCourses(
response.data
);
} catch (error) {
console.log(error);
}
}
Axios data can be displayed using FlatList.
<FlatList
data={users}
keyExtractor={
item =>
item.id.toString()
}
renderItem={({ item }) => (
<Text>
{item.name}
</Text>
)}
/>
This is useful when an API returns a list of records.
For larger applications, you can create an Axios instance with common configuration.
import axios from "axios";
const api =
axios.create({
baseURL:
"https://example.com/api",
timeout: 10000
});
export default api;
The instance can then be reused throughout the application.
import React, {
useEffect,
useState
} from "react";
import {
View,
Text,
ActivityIndicator,
FlatList
} from "react-native";
import axios from "axios";
export default function UsersScreen() {
const [users, setUsers] =
useState([]);
const [loading, setLoading] =
useState(true);
const [error, setError] =
useState("");
async function loadUsers() {
try {
setLoading(true);
setError("");
const response =
await axios.get(
"https://example.com/api/users"
);
setUsers(
response.data
);
} catch (error) {
setError(
"Unable to load users"
);
} finally {
setLoading(false);
}
}
useEffect(() => {
loadUsers();
}, []);
if (loading) {
return (
<ActivityIndicator />
);
}
if (error) {
return (
<Text>
{error}
</Text>
);
}
return (
<FlatList
data={users}
keyExtractor={
item =>
item.id.toString()
}
renderItem={({ item }) => (
<View>
<Text>
{item.name}
</Text>
</View>
)}
/>
);
}
This example combines Axios, useEffect, useState, error handling, loading handling and FlatList.
| Concept | Purpose |
|---|---|
| axios.get() | Retrieves data from an API |
| axios.post() | Sends data to an API |
| axios.put() | Updates a resource |
| axios.patch() | Partially updates a resource |
| axios.delete() | Requests deletion of a resource |
| response.data | Contains the response body |
| response.status | Contains the HTTP status code |
| axios.create() | Creates a reusable Axios instance |
React Native Screen
↓
Call API Function
↓
Axios Request
↓
Backend API
↓
Server Response
↓
Read response.data
↓
Update State
↓
Render UI
If Request Fails
↓
Catch Error
↓
Update Error State
↓
Show Error Message
Axios provides a convenient way to communicate with APIs from React Native applications. It supports common HTTP methods, request configuration, response handling and error handling.
npm install axios.import axios from "axios".axios.get() to retrieve data.axios.post() to send data.axios.put() and axios.patch() to update data.axios.delete() to request deletion.response.data to access response data.Question: Which Axios method is commonly used to retrieve data from an API?