How do you make API calls in React Native?

Making API Calls in React Native

In React Native, you can make API calls using fetch, Axios, or libraries like React Query for better state management.


1. Using fetch (Built-in JavaScript Method)

The fetch API is the easiest way to make network requests in React Native.

GET Request Example
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.


2. Using fetch with async/await

For 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.


3. Making a POST Request

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.


4. Using Axios (Alternative to fetch)

Axios is a popular library for API calls because it supports automatic JSON conversion and better error handling.

Install Axios
npm install axios
GET Request with 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.


5. Using React Query for Caching & Background Fetching

React Query helps with caching and automatic refetching.

Install React Query
npm install @tanstack/react-query
Setup 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.


6. Handling API Errors Properly

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.


7. Optimizing API Calls

* 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).