In this section, we will explore how to use Axios, a popular HTTP client, to make HTTP requests in a React Native application. Axios simplifies the process of making HTTP requests and handling responses, making it a powerful tool for interacting with APIs.
What is Axios?
Axios is a promise-based HTTP client for JavaScript that can be used in both the browser and Node.js environments. It provides a simple and intuitive API for making HTTP requests and handling responses.
Key Features of Axios:
- Supports the Promise API.
- Intercept request and response.
- Transform request and response data.
- Cancel requests.
- Automatic JSON data transformation.
Installing Axios
To use Axios in your React Native project, you need to install it via npm or yarn.
Making a GET Request
Let's start with a simple example of making a GET request to fetch data from an API.
Example: Fetching Data from an API
import React, { useEffect, useState } from 'react'; import { View, Text, ActivityIndicator, StyleSheet } from 'react-native'; import axios from 'axios'; const App = () => { const [data, setData] = useState(null); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); useEffect(() => { axios.get('https://jsonplaceholder.typicode.com/posts/1') .then(response => { setData(response.data); setLoading(false); }) .catch(error => { setError(error); setLoading(false); }); }, []); if (loading) { return <ActivityIndicator size="large" color="#0000ff" />; } if (error) { return <Text>Error: {error.message}</Text>; } return ( <View style={styles.container}> <Text style={styles.title}>{data.title}</Text> <Text>{data.body}</Text> </View> ); }; const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', padding: 16, }, title: { fontSize: 24, fontWeight: 'bold', marginBottom: 8, }, }); export default App;
Explanation:
- Importing Axios: We import Axios at the top of the file.
- State Management: We use
useState
to manage the state for data, loading, and error. - Fetching Data: Inside
useEffect
, we make a GET request to fetch data from the API. The response data is stored in thedata
state, and the loading state is set to false. - Error Handling: If an error occurs, it is caught and stored in the
error
state. - Conditional Rendering: We conditionally render a loading indicator, an error message, or the fetched data based on the state.
Making a POST Request
Next, let's see how to make a POST request to send data to an API.
Example: Sending Data to an API
import React, { useState } from 'react'; import { View, Text, TextInput, Button, StyleSheet } from 'react-native'; import axios from 'axios'; const App = () => { const [title, setTitle] = useState(''); const [body, setBody] = useState(''); const [response, setResponse] = useState(null); const handleSubmit = () => { axios.post('https://jsonplaceholder.typicode.com/posts', { title: title, body: body, }) .then(response => { setResponse(response.data); }) .catch(error => { console.error(error); }); }; return ( <View style={styles.container}> <TextInput style={styles.input} placeholder="Title" value={title} onChangeText={setTitle} /> <TextInput style={styles.input} placeholder="Body" value={body} onChangeText={setBody} /> <Button title="Submit" onPress={handleSubmit} /> {response && ( <View style={styles.responseContainer}> <Text style={styles.responseTitle}>Response:</Text> <Text>{JSON.stringify(response, null, 2)}</Text> </View> )} </View> ); }; const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', padding: 16, }, input: { height: 40, borderColor: 'gray', borderWidth: 1, marginBottom: 12, paddingHorizontal: 8, }, responseContainer: { marginTop: 16, }, responseTitle: { fontSize: 18, fontWeight: 'bold', }, }); export default App;
Explanation:
- State Management: We use
useState
to manage the state for the title, body, and response. - Handling Form Submission: The
handleSubmit
function is called when the form is submitted. It makes a POST request to send the title and body to the API. - Updating State: The response data is stored in the
response
state. - Rendering Response: If there is a response, it is displayed below the form.
Practical Exercise
Exercise: Fetch and Display a List of Users
- Create a new React Native component.
- Use Axios to fetch a list of users from the API:
https://jsonplaceholder.typicode.com/users
. - Display the list of users in a
FlatList
.
Solution:
import React, { useEffect, useState } from 'react'; import { View, Text, FlatList, ActivityIndicator, StyleSheet } from 'react-native'; import axios from 'axios'; const UsersList = () => { const [users, setUsers] = useState([]); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); useEffect(() => { axios.get('https://jsonplaceholder.typicode.com/users') .then(response => { setUsers(response.data); setLoading(false); }) .catch(error => { setError(error); setLoading(false); }); }, []); if (loading) { return <ActivityIndicator size="large" color="#0000ff" />; } if (error) { return <Text>Error: {error.message}</Text>; } return ( <View style={styles.container}> <FlatList data={users} keyExtractor={item => item.id.toString()} renderItem={({ item }) => ( <View style={styles.item}> <Text style={styles.name}>{item.name}</Text> <Text>{item.email}</Text> </View> )} /> </View> ); }; const styles = StyleSheet.create({ container: { flex: 1, padding: 16, }, item: { padding: 16, borderBottomWidth: 1, borderBottomColor: '#ccc', }, name: { fontSize: 18, fontWeight: 'bold', }, }); export default UsersList;
Explanation:
- Fetching Data: We fetch the list of users from the API using Axios.
- Displaying Data: We use a
FlatList
to display the list of users. - Error Handling: We handle errors and display an error message if an error occurs.
Conclusion
In this section, we learned how to use Axios to make HTTP requests in a React Native application. We covered making GET and POST requests, handling responses, and displaying data. Axios simplifies the process of interacting with APIs, making it a valuable tool for any React Native developer.
Next, we will explore how to handle network errors effectively in the following section.
React Native Course
Module 1: Introduction to React Native
- What is React Native?
- Setting Up the Development Environment
- Hello World App
- Understanding JSX
- Components and Props
Module 2: Core Components and Styling
- Core Components Overview
- Text, View, and Image
- Styling with Flexbox
- Handling User Input
- ScrollView and ListView
Module 3: State and Lifecycle
- State and Lifecycle Methods
- Handling Events
- Conditional Rendering
- Lists and Keys
- Forms and Controlled Components
Module 4: Navigation
- Introduction to React Navigation
- Stack Navigator
- Tab Navigator
- Drawer Navigator
- Passing Parameters to Routes
Module 5: Networking and Data
- Fetching Data with Fetch API
- Using Axios for HTTP Requests
- Handling Network Errors
- AsyncStorage for Local Data
- Integrating with REST APIs
Module 6: Advanced Concepts
Module 7: Deployment and Publishing
- Building for iOS
- Building for Android
- Publishing to App Store
- Publishing to Google Play
- Continuous Integration and Delivery