0
0
React Nativemobile~5 mins

Axios library in React Native

Choose your learning style9 modes available
Introduction

Axios helps your app talk to the internet easily. It fetches data from websites or sends data to them.

When you want to get data from a website to show in your app.
When you need to send user information to a server.
When your app needs to update information on the internet.
When you want to handle internet requests with simple code.
When you want to handle errors from internet requests clearly.
Syntax
React Native
import axios from 'axios';

axios.get(url)
  .then(response => {
    // handle success
  })
  .catch(error => {
    // handle error
  });
Use axios.get(url) to get data from a website.
Use axios.post(url, data) to send data to a website.
Examples
This gets data from the URL and prints it in the console.
React Native
axios.get('https://api.example.com/data')
  .then(response => console.log(response.data))
  .catch(error => console.error(error));
This sends a name to the server and prints the server's reply.
React Native
axios.post('https://api.example.com/user', {name: 'Anna'})
  .then(response => console.log(response.data))
  .catch(error => console.error(error));
Sample App

This React Native app uses Axios to get a todo item from the internet. It shows a loading spinner while waiting. If it fails, it shows an error message. If it works, it shows the todo details.

React Native
import React, {useEffect, useState} from 'react';
import {View, Text, ActivityIndicator} from 'react-native';
import axios from 'axios';

export default function App() {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    axios.get('https://jsonplaceholder.typicode.com/todos/1')
      .then(response => {
        setData(response.data);
        setLoading(false);
      })
      .catch(err => {
        setError('Failed to load data');
        setLoading(false);
      });
  }, []);

  if (loading) return <ActivityIndicator size="large" />;
  if (error) return <Text>{error}</Text>;

  return (
    <View style={{flex: 1, justifyContent: 'center', alignItems: 'center', padding: 20}}>
      <Text style={{fontSize: 18, fontWeight: 'bold'}}>Todo Item:</Text>
      <Text>ID: {data.id}</Text>
      <Text>Title: {data.title}</Text>
      <Text>Completed: {data.completed ? 'Yes' : 'No'}</Text>
    </View>
  );
}
OutputSuccess
Important Notes

Always handle errors to avoid app crashes.

Use useEffect in React Native to load data when the app starts.

Axios works well with promises, so use .then() and .catch() to handle results.

Summary

Axios makes internet requests simple in React Native apps.

Use axios.get to fetch data and axios.post to send data.

Always handle loading and errors for a good user experience.