Skip to content

React Native - HTTP

This chapter demonstrates how to fetch data from a remote server using HTTP requests in React Native. We’ll use the built-in fetch API, which is a modern standard for making network requests in JavaScript environments.

We will create a component that fetches a list of posts from a public API (jsonplaceholder.typicode.com) when it mounts and displays the title of the first post. We’ll use useEffect to trigger the data fetch and useState to store the fetched data and loading/error states.

DataFetcher.js

import React, { useState, useEffect } from 'react';
import { View, Text, StyleSheet, ActivityIndicator, Button } from 'react-native';
const DataFetcher = () => {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
const fetchData = async () => {
setLoading(true);
setError(null);
try {
const response = await fetch('https://jsonplaceholder.typicode.com/posts/1');
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const jsonResponse = await response.json();
setData(jsonResponse);
} catch (e) {
console.error("Fetch error: ", e);
setError(e.message);
} finally {
setLoading(false);
}
};
useEffect(() => {
fetchData(); // Fetch data when component mounts
// Optional: Cleanup function if needed (e.g., to cancel fetch)
// return () => {
// // cleanup logic
// };
}, []); // Empty dependency array means this effect runs once on mount
if (loading) {
return (
<View style={styles.container}>
<ActivityIndicator size="large" color="#0000ff" />
<Text>Loading data...</Text>
</View>
);
}
if (error) {
return (
<View style={styles.container}>
<Text style={styles.errorText}>Error fetching data: {error}</Text>
<Button title="Retry" onPress={fetchData} />
</View>
);
}
return (
<View style={styles.container}>
{data ? (
<View>
<Text style={styles.title}>Fetched Post Title:</Text>
<Text style={styles.bodyText}>{data.title}</Text>
<Text style={styles.title}>Post Body:</Text>
<Text style={styles.bodyText}>{data.body}</Text>
</View>
) : (
<Text>No data fetched.</Text>
)}
<Button title="Fetch Again" onPress={fetchData} />
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
padding: 20,
},
title: {
fontSize: 18,
fontWeight: 'bold',
marginTop: 10,
},
bodyText: {
fontSize: 16,
marginVertical: 5,
textAlign: 'center',
},
errorText: {
color: 'red',
fontSize: 16,
marginBottom: 10,
}
});
export default DataFetcher;
  • State Variables: data stores the fetched response, loading indicates if the request is in progress, and error stores any error message.
  • useEffect Hook: The fetchData function is called within useEffect. The empty dependency array [] ensures this effect runs only once after the initial render (similar to componentDidMount in class components).
  • async/await: Simplifies asynchronous code, making it look more synchronous. await fetch(...) pauses execution until the promise resolves.
  • Error Handling: We use a try...catch block to handle potential network errors or issues with the response (e.g., response.ok checks for HTTP status codes like 404 or 500).
  • Loading and Error UI: The component renders different UI based on the loading and error states, providing better user feedback.
  • response.json(): This method on the Response object parses the response body as JSON.

When this component is rendered, it will show a loading indicator, then fetch data from the URL. If successful, it displays the title and body of the fetched post. If an error occurs, an error message is shown with a retry button.

Making Other Types of Requests (POST, PUT, DELETE)

Section titled “Making Other Types of Requests (POST, PUT, DELETE)”

The fetch API can also be used for other HTTP methods like POST, PUT, DELETE. You need to provide a second argument to fetch with a configuration object:

const postData = async () => {
try {
const response = await fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST', // Specify the method
headers: {
'Content-Type': 'application/json', // Specify content type
// 'Authorization': 'Bearer YOUR_TOKEN_HERE', // Example for auth
},
body: JSON.stringify({ // Convert JavaScript object to JSON string
title: 'foo',
body: 'bar',
userId: 1,
}),
});
const jsonResponse = await response.json();
console.log('POST Response:', jsonResponse);
} catch (error) {
console.error('Error posting data:', error);
}
};

For more complex scenarios or if you prefer a library with more features (like automatic request/response transformation, interceptors), consider using libraries like Axios. However, fetch is powerful and sufficient for many use cases.

Further reading: MDN Fetch API documentation