Axios helps your app talk to the internet easily. It fetches data from websites or sends data to them.
Axios library in React Native
Introduction
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
React Native
axios.get('https://api.example.com/data')
.then(response => console.log(response.data))
.catch(error => console.error(error));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> ); }
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.
Practice
1. What is the main purpose of using the
Axios library in a React Native app?easy
Solution
Step 1: Understand Axios functionality
Axios is a library designed to simplify making HTTP requests like GET and POST.Step 2: Identify Axios use in React Native
It helps fetch data from servers or send data to them, which is essential for dynamic apps.Final Answer:
To make HTTP requests to fetch or send data -> Option AQuick Check:
Axios = HTTP requests [OK]
Hint: Axios is for internet requests, not styling or navigation [OK]
Common Mistakes:
- Confusing Axios with styling libraries
- Thinking Axios manages navigation
- Assuming Axios stores data locally
2. Which of the following is the correct syntax to make a GET request using Axios in React Native?
easy
Solution
Step 1: Recall Axios GET method
The correct method to fetch data isaxios.get(url).Step 2: Check other options
axios.fetchis not a valid Axios method,axios.postsends data, andaxios.requestis more generic but requires config.Final Answer:
axios.get('https://api.example.com/data') -> Option BQuick Check:
GET request = axios.get() [OK]
Hint: Use axios.get() for fetching data [OK]
Common Mistakes:
- Using axios.fetch which does not exist
- Confusing get with post method
- Using axios.request without config object
3. What will be logged to the console after this Axios GET request succeeds?
axios.get('https://api.example.com/user')
.then(response => console.log(response.data.name))
.catch(error => console.log('Error'));
Assuming the server responds with { "name": "Alice" }.medium
Solution
Step 1: Understand Axios response structure
Axios returns a response object where the actual data is insideresponse.data.Step 2: Access the name property
The code logsresponse.data.name, which is "Alice" from the server response.Final Answer:
Alice -> Option CQuick Check:
response.data.name = Alice [OK]
Hint: Access data via response.data in Axios [OK]
Common Mistakes:
- Logging response instead of response.data
- Expecting data directly without .data
- Not handling promise with then/catch
4. Identify the error in this Axios POST request code snippet:
axios.post('https://api.example.com/login',
{ username: 'user1', password: 'pass123' }
).then(response => {
console.log('Login successful');
}).catch(error => {
console.log('Login failed');
});medium
Solution
Step 1: Review Axios POST syntax
Axios.post takes URL and data object as parameters, which is correct here.Step 2: Check for syntax or usage errors
The code uses promise chaining with then/catch correctly; await is optional.Final Answer:
No error, code is correct -> Option AQuick Check:
Axios.post with object data is valid [OK]
Hint: Axios.post accepts object data without await [OK]
Common Mistakes:
- Thinking await is mandatory with then/catch
- Assuming data must be JSON stringified manually
- Confusing URL format with error
5. You want to fetch user data and show a loading message while waiting. Which code snippet correctly uses Axios with React Native hooks to handle loading and errors?
hard
Solution
Step 1: Initialize loading state correctly
Loading should start as false, then set to true when request starts.Step 2: Set loading true before Axios call and false after response or error
This ensures UI shows loading while waiting and hides it after.Final Answer:
Initialize loading false, set true before request, false after -> Option DQuick Check:
Loading true during request = const [loading, setLoading] = useState(false); useEffect(() => { setLoading(true); axios.get('/user') .then(() => setLoading(false)) .catch(() => setLoading(false)); }, []); [OK]
Hint: Set loading true before request, false after response [OK]
Common Mistakes:
- Starting loading as true but not setting it properly
- Setting loading true after request finishes
- Not handling loading state at all
Recommended
Ready to prove it?
Pass the test and this pattern moves unknown
10 questions ~5 mineasy hard
