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.
response.json()catch()The basic syntax of the Fetch API involves calling fetch(url, options). It returns a Promise that resolves to a Response object.
// 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);
});
// 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;
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.
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.
catch()async/await for cleaner syntax