How to Fetch Data in React Native: Simple Guide
In React Native, you fetch data using the
fetch() API, which lets you request data from a server asynchronously. You call fetch() with a URL, then handle the response with then() or async/await to update your app's state and UI.Syntax
The basic syntax to fetch data is using the fetch() function with a URL string. It returns a promise that resolves to a response object. You then convert this response to JSON and use the data.
fetch(url): Starts the request..then(response => response.json()): Parses the response as JSON..then(data => { ... }): Uses the data..catch(error => { ... }): Handles errors.
javascript
fetch('https://example.com/data') .then(response => response.json()) .then(data => { // use the data here }) .catch(error => { // handle errors here });
Example
This example shows a React Native component that fetches user data from a public API when the component loads. It displays the user's name or a loading message.
javascript
import React, { useEffect, useState } from 'react'; import { View, Text, ActivityIndicator } from 'react-native'; export default function UserData() { const [user, setUser] = useState(null); const [loading, setLoading] = useState(true); useEffect(() => { async function fetchUser() { try { const response = await fetch('https://jsonplaceholder.typicode.com/users/1'); const data = await response.json(); setUser(data); } catch (error) { console.error('Error fetching user:', error); } finally { setLoading(false); } } fetchUser(); }, []); if (loading) { return <ActivityIndicator size="large" />; } return ( <View style={{ padding: 20 }}> <Text>User Name: {user?.name}</Text> </View> ); }
Output
Displays a loading spinner, then shows: User Name: Leanne Graham
Common Pitfalls
Common mistakes when fetching data in React Native include:
- Not handling errors, which can crash the app or leave it stuck loading.
- Forgetting to update state inside
useEffector missing dependency arrays, causing infinite loops. - Not showing a loading state, confusing users while data loads.
- Trying to fetch data synchronously instead of using async/await or promises.
javascript
/* Wrong: Missing error handling and loading state */ useEffect(() => { fetch('https://jsonplaceholder.typicode.com/users/1') .then(response => response.json()) .then(data => setUser(data)); }, []); /* Right: With error handling and loading state */ useEffect(() => { async function fetchData() { try { const response = await fetch('https://jsonplaceholder.typicode.com/users/1'); const data = await response.json(); setUser(data); } catch (error) { console.error(error); } finally { setLoading(false); } } fetchData(); }, []);
Quick Reference
Remember these tips when fetching data in React Native:
- Always handle errors with
try/catchor.catch(). - Use
useEffectto fetch data on component load. - Show a loading indicator while waiting for data.
- Update state with fetched data to trigger UI refresh.
Key Takeaways
Use the fetch() API with async/await or promises to get data from a server.
Always handle loading and error states to improve user experience.
Fetch data inside useEffect to run it when the component mounts.
Update React Native state with fetched data to refresh the UI.
Avoid infinite loops by providing an empty dependency array to useEffect.