← Back to Chapters

React Native Fetch API

? React Native Fetch API

? Quick Overview

The fetch() API in React Native is used to make HTTP network requests such as GET, POST, PUT, and DELETE. It works similarly to the browser Fetch API and returns Promises for handling asynchronous data.

? Key Concepts

  • Asynchronous network requests
  • Promise-based API
  • JSON parsing using response.json()
  • Error handling with catch()
  • Used for REST API communication

? Syntax / Theory

The basic syntax of the Fetch API involves calling fetch(url, options). It returns a Promise that resolves to a Response object.

? View Code Example
// Basic fetch syntax in React Native
fetch("https://example.com/api/data")
.then(response => response.json())
.then(data => {
console.log(data);
})
.catch(error => {
console.error(error);
});

? Code Example(s)

? View Code Example
// Fetching data inside a React Native component
import React, { useEffect, useState } from "react";
import { View, Text } from "react-native";

const App = () => {
const [users, setUsers] = useState([]);

useEffect(() => {
fetch("https://jsonplaceholder.typicode.com/users")
.then(response => response.json())
.then(data => setUsers(data))
.catch(error => console.log(error));
}, []);

return (

{users.map(user => (
{user.name}
))}

);
};

export default App;

? Live Output / Explanation

? What Happens?

When the component loads, the API request is triggered. The fetched JSON data is stored in state and rendered as a list of names on the screen.

? Interactive Example / Visualization

Click the button below to mimic a React Native fetch() call. This will hit a real API endpoint and display the results, just like in a mobile app.

// API Response will appear here...

?️ Use Cases

  • Fetching user data from a backend
  • Submitting forms to a server
  • Loading dynamic content
  • Integrating third-party APIs

✅ Tips & Best Practices

  • Always handle errors using catch()
  • Use async/await for cleaner syntax
  • Show loading indicators during network calls
  • Avoid fetching data directly inside render

? Try It Yourself

  1. Fetch posts instead of users
  2. Display data in a FlatList
  3. Add a loading spinner
  4. Handle API failure gracefully