← Back to Chapters

Axios Basics in React Native

? Axios Basics in React Native

✨ Quick Overview

Axios is a popular HTTP client used in React Native to communicate with REST APIs. It simplifies making network requests such as GET, POST, PUT, and DELETE.

? Key Concepts

  • Promise-based HTTP client
  • Supports async/await
  • Automatic JSON transformation
  • Works on Android and iOS

? Syntax / Theory

Axios methods return promises. You can handle responses using .then() or async/await.

? View Code Example
// Import axios library
import axios from "axios";

// Make a GET request
axios.get("https://jsonplaceholder.typicode.com/posts")
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error(error);
});

? Live Output / Explanation

What Happens?

The API returns a list of posts in JSON format which is logged to the console.

? Interactive Example

The following example mimics a React Native app component. Click the button to fetch real data using Axios.

? App View
Click "Fetch Users" to load data...
 
Console Log: Waiting for action...

? Code Implementation

View React Native Code Logic
// Fetch data on component mount or button press
import React, { useState } from "react";
import { Text, View, Button, FlatList } from "react-native";
import axios from "axios";

export default function App() {
  const [data, setData] = useState([]);
  const [loading, setLoading] = useState(false);

  const fetchData = () => {
    setLoading(true);
    axios.get("https://jsonplaceholder.typicode.com/users")
      .then(res => {
        setData(res.data);
        setLoading(false);
      })
      .catch(err => console.error(err));
  };

  return (
    <View>
      <Button title="Fetch Users" onPress={fetchData} />
      {loading ? <Text>Loading...</Text> : null}
      <FlatList 
        data={data}
        keyExtractor={item => item.id.toString()}
        renderItem={({item}) => <Text>{item.name}</Text>} 
      />
    </View>
  );
}

? Use Cases

  • Fetching API data
  • Submitting forms
  • Authentication requests
  • Uploading files

✅ Tips & Best Practices

  • Always handle errors using catch
  • Use environment variables for base URLs
  • Create reusable axios instances

? Try It Yourself

  • Fetch posts from another API endpoint
  • Display data in FlatList
  • Add loading and error states