Setting up Axios for network requests in a React Native application

NOVASOLUTIONS.TECHNOLOGY is engaged in the development, support and maintenance of iOS, Android, PWA mobile applications. We have extensive experience and expertise in publishing mobile applications in popular markets like Google Play, App Store, Amazon, AppGallery and others.
Development and support of all types of mobile applications:
Information and entertainment mobile applications
News apps, games, reference guides, online catalogs, weather apps, fitness and health apps, travel apps, educational apps, social networks and messengers, quizzes, blogs and podcasts, forums, aggregators
E-commerce mobile applications
Online stores, B2B apps, marketplaces, online exchanges, cashback services, exchanges, dropshipping platforms, loyalty programs, food and goods delivery, payment systems.
Business process management mobile applications
CRM systems, ERP systems, project management, sales team tools, financial management, production management, logistics and delivery management, HR management, data monitoring systems
Electronic services mobile applications
Classified ads platforms, online schools, online cinemas, electronic service platforms, cashback platforms, video hosting, thematic portals, online booking and scheduling platforms, online trading platforms

These are just some of the types of mobile applications we work with, and each of them may have its own specific features and functionality, tailored to the specific needs and goals of the client.

Showing 1 of 1 servicesAll 1735 services
Setting up Axios for network requests in a React Native application
Medium
from 1 business day to 3 business days
FAQ
Our competencies:
Development stages
Latest works
  • image_mobile-applications_feedme_467_0.webp
    Development of a mobile application for FEEDME
    756
  • image_mobile-applications_xoomer_471_0.webp
    Development of a mobile application for XOOMER
    624
  • image_mobile-applications_rhl_428_0.webp
    Development of a mobile application for RHL
    1052
  • image_mobile-applications_zippy_411_0.webp
    Development of a mobile application for ZIPPY
    947
  • image_mobile-applications_affhome_429_0.webp
    Development of a mobile application for Affhome
    862
  • image_mobile-applications_flavors_409_0.webp
    Development of a mobile application for the FLAVORS company
    445

Setting up Axios for network requests in React Native applications

In React Native you can use the native fetch, but Axios provides interceptors, automatic JSON transformation, request cancellation via AbortController and convenient error handling. For a production application this is more important than saving one package.

Installation and basic client

npm install axios

Create a typed API client — don't use global axios directly:

import axios, { AxiosInstance, InternalAxiosRequestConfig } from 'axios';

const apiClient: AxiosInstance = axios.create({
  baseURL: process.env.API_BASE_URL ?? 'https://api.example.com/v1',
  timeout: 10_000,
  headers: { 'Content-Type': 'application/json' },
});

Interceptors

Auth interceptor with token refresh:

apiClient.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    const token = tokenStore.getAccessToken();
    if (token) config.headers.Authorization = `Bearer ${token}`;
    return config;
  }
);

apiClient.interceptors.response.use(
  (response) => response,
  async (error) => {
    const originalRequest = error.config;
    if (error.response?.status === 401 && !originalRequest._retry) {
      originalRequest._retry = true;
      try {
        const newToken = await tokenStore.refresh();
        originalRequest.headers.Authorization = `Bearer ${newToken}`;
        return apiClient(originalRequest);
      } catch {
        tokenStore.clear();
        navigationRef.navigate('Login');
      }
    }
    return Promise.reject(error);
  }
);

The _retry flag prevents infinite loop on refresh error. Without it 401 on /refresh → new refresh → 401 → infinity.

Logging in dev mode via axios-logger or custom interceptor:

if (__DEV__) {
  apiClient.interceptors.request.use((config) => {
    console.log(`→ ${config.method?.toUpperCase()} ${config.url}`);
    return config;
  });
}

Response typing

interface PaginatedResponse<T> {
  data: T[];
  meta: { total: number; page: number; perPage: number };
}

async function getProducts(page: number): Promise<PaginatedResponse<Product>> {
  const { data } = await apiClient.get<PaginatedResponse<Product>>('/products', {
    params: { page, per_page: 20 },
  });
  return data;
}

Request cancellation

React Native 0.71+ supports AbortController natively. Axios integrates with it:

const controller = new AbortController();
apiClient.get('/feed', { signal: controller.signal });

// In useEffect cleanup:
return () => controller.abort();

Without canceling requests in useEffect cleanup — possible setState on unmounted component warning and memory leak when quickly navigating between screens.

Error handling

function isAxiosError(error: unknown): error is AxiosError {
  return axios.isAxiosError(error);
}

try {
  await getProducts(1);
} catch (error) {
  if (isAxiosError(error)) {
    if (!error.response) {
      // Network error — no connection
    } else {
      const status = error.response.status;
      // 400, 422, 500...
    }
  }
}

Integration with React Query (@tanstack/react-query) or SWR moves error handling and caching to the library level — recommended for most applications.

Timelines

Basic setup with auth interceptor: 3–6 hours. With typing, React Query and error handling: 1–2 days. Pricing calculated individually.