In this section, we will learn how to integrate REST APIs into a React Native application. REST APIs are a common way to interact with backend services, allowing us to fetch, create, update, and delete data. We will cover the following topics:
- Understanding REST APIs
- Setting Up Axios
- Making GET Requests
- Making POST Requests
- Handling PUT and DELETE Requests
- Error Handling
- Practical Exercise
- Understanding REST APIs
REST (Representational State Transfer) is an architectural style for designing networked applications. It relies on a stateless, client-server, cacheable communications protocol -- the HTTP. RESTful applications use HTTP requests to perform CRUD (Create, Read, Update, Delete) operations.
Key Concepts:
- Endpoint: A specific URL where an API can be accessed.
- HTTP Methods: Common methods include GET, POST, PUT, DELETE.
- Status Codes: Indicate the result of the HTTP request (e.g., 200 for success, 404 for not found).
- Setting Up Axios
Axios is a popular HTTP client for making requests. It is promise-based and works in both the browser and Node.js environments.
Installation:
Basic Setup:
import axios from 'axios'; const api = axios.create({ baseURL: 'https://api.example.com', timeout: 1000, headers: {'Authorization': 'Bearer YOUR_TOKEN'} });
- Making GET Requests
GET requests are used to retrieve data from a server.
Example:
import React, { useEffect, useState } from 'react'; import { View, Text, ActivityIndicator } from 'react-native'; import axios from 'axios'; const FetchData = () => { const [data, setData] = useState(null); const [loading, setLoading] = useState(true); useEffect(() => { axios.get('https://api.example.com/data') .then(response => { setData(response.data); setLoading(false); }) .catch(error => { console.error(error); setLoading(false); }); }, []); if (loading) { return <ActivityIndicator />; } return ( <View> <Text>{JSON.stringify(data, null, 2)}</Text> </View> ); }; export default FetchData;
Explanation:
- useEffect: Fetches data when the component mounts.
- axios.get: Makes a GET request to the specified URL.
- setData: Updates the state with the fetched data.
- ActivityIndicator: Displays a loading spinner while data is being fetched.
- Making POST Requests
POST requests are used to send data to a server.
Example:
import React, { useState } from 'react'; import { View, TextInput, Button, Text } from 'react-native'; import axios from 'axios'; const PostData = () => { const [input, setInput] = useState(''); const [response, setResponse] = useState(null); const handleSubmit = () => { axios.post('https://api.example.com/data', { data: input }) .then(response => { setResponse(response.data); }) .catch(error => { console.error(error); }); }; return ( <View> <TextInput value={input} onChangeText={setInput} placeholder="Enter data" /> <Button title="Submit" onPress={handleSubmit} /> {response && <Text>{JSON.stringify(response, null, 2)}</Text>} </View> ); }; export default PostData;
Explanation:
- TextInput: Captures user input.
- axios.post: Sends a POST request with the input data.
- handleSubmit: Handles the form submission and updates the state with the server response.
- Handling PUT and DELETE Requests
PUT requests are used to update existing data, while DELETE requests are used to remove data.
PUT Example:
axios.put('https://api.example.com/data/1', { data: 'Updated data' }) .then(response => { console.log(response.data); }) .catch(error => { console.error(error); });
DELETE Example:
axios.delete('https://api.example.com/data/1') .then(response => { console.log(response.data); }) .catch(error => { console.error(error); });
- Error Handling
Proper error handling is crucial for a robust application.
Example:
axios.get('https://api.example.com/data') .then(response => { console.log(response.data); }) .catch(error => { if (error.response) { // Server responded with a status other than 200 range console.error('Error response:', error.response.data); } else if (error.request) { // Request was made but no response received console.error('Error request:', error.request); } else { // Something else happened console.error('Error message:', error.message); } });
- Practical Exercise
Task:
Create a simple React Native app that fetches a list of users from a public API and displays them in a list.
Steps:
- Set up a new React Native project.
- Install Axios.
- Create a component that fetches data from
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 } from 'react-native'; import axios from 'axios'; const UserList = () => { const [users, setUsers] = useState([]); const [loading, setLoading] = useState(true); useEffect(() => { axios.get('https://jsonplaceholder.typicode.com/users') .then(response => { setUsers(response.data); setLoading(false); }) .catch(error => { console.error(error); setLoading(false); }); }, []); if (loading) { return <ActivityIndicator />; } return ( <View> <FlatList data={users} keyExtractor={item => item.id.toString()} renderItem={({ item }) => ( <View> <Text>{item.name}</Text> <Text>{item.email}</Text> </View> )} /> </View> ); }; export default UserList;
Explanation:
- FlatList: Efficiently renders a list of users.
- keyExtractor: Ensures each list item has a unique key.
- renderItem: Defines how each user item should be displayed.
Conclusion
In this section, we covered the basics of integrating REST APIs into a React Native application using Axios. We learned how to make GET, POST, PUT, and DELETE requests, handle errors, and implemented a practical exercise to reinforce these concepts. Understanding how to interact with REST APIs is essential for building dynamic and data-driven applications. In the next module, we will explore more advanced concepts and techniques to further enhance our React Native skills.
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