In React Native, you can make API calls using fetch, Axios, or libraries like React Query for better state management.
fetch (Built-in JavaScript Method)The fetch API is the easiest way to make network requests in React Native.
import React, { useEffect, useState } from 'react';
import { View, Text, ActivityIndicator } from 'react-native';
const App = () => {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
fetch('https://jsonplaceholder.typicode.com/posts/1')
.then(response => response.json())
.then(json => {
setData(json);
setLoading(false);
})
.catch(error => console.error('Error fetching data:', error));
}, []);
return (
<View>
{loading ? (
<ActivityIndicator size="large" color="blue" />
) : (
<Text>{data?.title}</Text>
)}
</View>
);
};
export default App;
* Handles API calls, updates state, and displays a loading indicator.
fetch with async/awaitFor better readability, use async/await.
const fetchData = async () => {
try {
const response = await fetch('https://jsonplaceholder.typicode.com/posts/1');
const json = await response.json();
setData(json);
} catch (error) {
console.error('Error:', error);
}
};
* Cleaner syntax with error handling.
Send data to an API using fetch with POST method.
const sendData = async () => {
try {
const response = await fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ title: 'React Native', body: 'Hello API!', userId: 1 }),
});
const json = await response.json();
console.log('Response:', json);
} catch (error) {
console.error('Error:', error);
}
};
* Sends JSON data to an API.
fetch)Axios is a popular library for API calls because it supports automatic JSON conversion and better error handling.
npm install axios
import axios from 'axios';
const fetchData = async () => {
try {
const response = await axios.get('https://jsonplaceholder.typicode.com/posts/1');
console.log(response.data);
} catch (error) {
console.error('Error:', error);
}
};
* Easier error handling and cleaner syntax.
React Query helps with caching and automatic refetching.
npm install @tanstack/react-query
import { QueryClient, QueryClientProvider, useQuery } from '@tanstack/react-query';
import { View, Text, ActivityIndicator } from 'react-native';
import axios from 'axios';
const queryClient = new QueryClient();
const fetchPost = async () => {
const { data } = await axios.get('https://jsonplaceholder.typicode.com/posts/1');
return data;
};
const Post = () => {
const { data, isLoading } = useQuery(['post'], fetchPost);
if (isLoading) return <ActivityIndicator size="large" color="blue" />;
return <Text>{data.title}</Text>;
};
const App = () => (
<QueryClientProvider client={queryClient}>
<Post />
</QueryClientProvider>
);
export default App;
* Caches responses and automatically refetches data when needed.
Always include error handling when making API calls.
const fetchData = async () => {
try {
const response = await fetch('https://jsonplaceholder.typicode.com/posts/1');
if (!response.ok) throw new Error('Network response was not ok');
const json = await response.json();
setData(json);
} catch (error) {
console.error('API Error:', error.message);
}
};
* Prevents crashes by catching API errors.
* Use caching (e.g., React Query, Redux Toolkit Query).
* Debounce API calls to avoid excessive requests.
* Use background fetch for real-time updates.
* Paginate large datasets (use ?page=1&limit=10).