0
0
React-nativeHow-ToBeginner ยท 4 min read

How to Use Axios in React Native for API Requests

To use axios in React Native, first install it with npm install axios. Then import axios in your component and use methods like axios.get() or axios.post() to make HTTP requests and handle responses with promises or async/await.
๐Ÿ“

Syntax

The basic syntax for using axios involves calling HTTP methods like get, post, put, or delete on the axios object. Each method returns a promise that resolves with the response data.

  • axios.get(url, config): Fetch data from the given URL.
  • axios.post(url, data, config): Send data to the server.
  • config: Optional settings like headers.
javascript
import axios from 'axios';

axios.get('https://example.com/api/data')
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    console.error(error);
  });
Output
Logs the data received from the API or an error if the request fails.
๐Ÿ’ป

Example

This example shows a React Native component that fetches user data from an API using axios when a button is pressed. It displays the user's name or an error message.

javascript
import React, { useState } from 'react';
import { View, Text, Button } from 'react-native';
import axios from 'axios';

export default function UserFetcher() {
  const [userName, setUserName] = useState('');
  const [error, setError] = useState('');

  const fetchUser = async () => {
    try {
      const response = await axios.get('https://jsonplaceholder.typicode.com/users/1');
      setUserName(response.data.name);
      setError('');
    } catch (err) {
      setError('Failed to fetch user');
      setUserName('');
    }
  };

  return (
    <View style={{ padding: 20 }}>
      <Button title="Get User" onPress={fetchUser} />
      {userName ? <Text>User Name: {userName}</Text> : null}
      {error ? <Text style={{ color: 'red' }}>{error}</Text> : null}
    </View>
  );
}
Output
When the button is pressed, the app shows 'User Name: Leanne Graham' or 'Failed to fetch user' if there is an error.
โš ๏ธ

Common Pitfalls

Common mistakes when using axios in React Native include:

  • Not installing axios before importing it.
  • Forgetting to handle promise rejections with catch or try/catch.
  • Using incorrect URLs or missing https:// which causes network errors.
  • Not setting headers when required by the API.

Always test your requests and handle errors gracefully.

javascript
/* Wrong: Missing error handling */
axios.get('https://example.com/api')
  .then(response => console.log(response.data));

/* Right: With error handling */
axios.get('https://example.com/api')
  .then(response => console.log(response.data))
  .catch(error => console.error('Error:', error));
Output
Logs data if successful, or logs 'Error:' with error details if failed.
๐Ÿ“Š

Quick Reference

Here is a quick summary of axios usage in React Native:

FeatureDescriptionExample
GET requestFetch data from a URLaxios.get('https://api.com/data')
POST requestSend data to serveraxios.post('https://api.com/data', {name: 'John'})
Handling responseUse .then() or async/awaitconst res = await axios.get(url)
Error handlingUse .catch() or try/catchaxios.get(url).catch(err => console.error(err))
Setting headersAdd headers in configaxios.get(url, { headers: { Authorization: 'token' } })
โœ…

Key Takeaways

Install axios with npm and import it before use in React Native.
Use axios methods like get and post to make HTTP requests and handle responses with promises or async/await.
Always handle errors to avoid app crashes and provide user feedback.
Check your API URLs and headers carefully to avoid network errors.
Use the quick reference table to remember common axios patterns.