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
axiosbefore importing it. - Forgetting to handle promise rejections with
catchor 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:
| Feature | Description | Example |
|---|---|---|
| GET request | Fetch data from a URL | axios.get('https://api.com/data') |
| POST request | Send data to server | axios.post('https://api.com/data', {name: 'John'}) |
| Handling response | Use .then() or async/await | const res = await axios.get(url) |
| Error handling | Use .catch() or try/catch | axios.get(url).catch(err => console.error(err)) |
| Setting headers | Add headers in config | axios.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.