Axios is a popular HTTP client used in React Native to communicate with REST APIs. It simplifies making network requests such as GET, POST, PUT, and DELETE.
Axios methods return promises. You can handle responses using .then() or async/await.
// Import axios library
import axios from "axios";
// Make a GET request
axios.get("https://jsonplaceholder.typicode.com/posts")
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error(error);
});
The API returns a list of posts in JSON format which is logged to the console.
The following example mimics a React Native app component. Click the button to fetch real data using Axios.
// Fetch data on component mount or button press
import React, { useState } from "react";
import { Text, View, Button, FlatList } from "react-native";
import axios from "axios";
export default function App() {
const [data, setData] = useState([]);
const [loading, setLoading] = useState(false);
const fetchData = () => {
setLoading(true);
axios.get("https://jsonplaceholder.typicode.com/users")
.then(res => {
setData(res.data);
setLoading(false);
})
.catch(err => console.error(err));
};
return (
<View>
<Button title="Fetch Users" onPress={fetchData} />
{loading ? <Text>Loading...</Text> : null}
<FlatList
data={data}
keyExtractor={item => item.id.toString()}
renderItem={({item}) => <Text>{item.name}</Text>}
/>
</View>
);
}
catch