Using Axios for HTTP Communication in React Native
Course: React Native Training
Topic: Using Axios for HTTP Communication
Course Link: React Native Training Course
Demo Link: Register for a Course Demo
Academy Website: JustAcademy
1. Introduction to Axios
Axios is a Promise-based HTTP client library used to send HTTP requests from JavaScript applications. In React Native, Axios allows mobile applications to communicate with backend servers and REST APIs to retrieve, create, update, and delete data.
For example, a shopping application can use Axios to retrieve products, submit orders, update a user's profile, and remove items from a cart. A social networking application can use it to load profiles, retrieve posts, and submit comments.
React Native includes the Fetch API for networking, but Axios provides additional conveniences such as automatic JSON response transformation, configurable request timeouts, request and response interceptors, and a centralized configuration system.
1.1 What Is HTTP Communication?
HTTP communication is the exchange of requests and responses between a client and a server. A React Native application acts as the client, while a backend API receives requests, processes them, and returns responses.
A typical HTTP communication process involves:
- The user opens a screen or performs an action.
- The application creates an HTTP request.
- Axios sends the request to the API endpoint.
- The server processes the request and returns a response.
- Axios provides the response or reports an error.
- The React Native component updates its state and renders the appropriate interface.
1.2 Why Use Axios in React Native?
- To communicate with REST APIs and backend services.
- To retrieve data from remote servers.
- To submit forms and create resources.
- To update and delete existing resources.
- To configure common request headers and base URLs.
- To handle HTTP errors with a consistent error-handling approach.
- To add authentication headers through interceptors.
- To configure request timeouts and cancel unnecessary requests.
2. Learning Objectives
After completing this topic, learners should be able to:
- Understand Axios and its role in React Native development.
- Install and configure Axios in a project.
- Send GET, POST, PUT, PATCH, and DELETE requests.
- Understand Axios request configuration and response objects.
- Pass query parameters, headers, and JSON request bodies.
- Display API data using React Native components.
- Manage loading, success, empty, and error states.
- Handle authentication using authorization headers.
- Configure Axios instances and interceptors.
- Use request cancellation and timeout configuration.
- Apply security and performance best practices.
3. Installing Axios
Before using Axios, install it in your React Native project. Axios is a JavaScript library and normally does not require separate native module linking.
3.1 Installation Using npm
npm install axios
3.2 Installation Using Yarn
yarn add axios
3.3 Importing Axios
import axios from 'axios';
Once installed, Axios can be imported into components, custom hooks, and API utility files. For larger applications, creating a shared Axios instance is usually more maintainable than configuring every request separately.
4. Understanding Axios Architecture
Axios provides methods that make HTTP requests and return Promises. These Promises resolve with a response object when the request is considered successful under the configured status rules, or reject with an error when the request fails.
4.1 Important Axios Components
| Component |
Description |
| Axios methods |
Methods such as get(), post(), put(), patch(), and delete(). |
| Request configuration |
Options such as URL, headers, parameters, timeout, and request body. |
| Response object |
Contains returned data, status, headers, and request configuration. |
| Axios instance |
A reusable client with shared configuration. |
| Interceptors |
Functions that process requests or responses before application code handles them. |
| Error object |
Provides information about HTTP failures, network errors, or request setup problems. |
5. Understanding the Axios Response Object
When an Axios request succeeds, it returns a response object containing information about the HTTP response.
5.1 Example Response
{
data: {
id: 1,
name: "Aarav Sharma",
email: "[email protected]"
},
status: 200,
statusText: "OK",
headers: {},
config: {},
request: {}
}
This is a simplified illustration of an Axios response object. Actual headers and configuration properties depend on the request and runtime.
5.2 Important Response Properties
| Property |
Purpose |
response.data |
The response body, often already parsed into a JavaScript object or array. |
response.status |
The HTTP status code, such as 200 or 201. |
response.statusText |
The status text, when provided by the adapter. |
response.headers |
Response headers. |
response.config |
The configuration used for the request. |
response.request |
Information about the underlying request, depending on the adapter. |
In many Axios applications, developers mainly use response.data to access the returned API information.
6. Making a GET Request with Axios
The GET method is used to retrieve information from an API. Axios provides the axios.get() method for this purpose.
6.1 Basic GET Request
import axios from 'axios';
async function getUsers() {
const response = await axios.get(
'https://jsonplaceholder.typicode.com/users'
);
return response.data;
}
The example uses a public demonstration API. The returned data is an array of sample users.
6.2 Understanding the Code
axios.get() sends a GET request.
await waits for the Promise to settle.
response contains the HTTP response information.
response.data provides the parsed response body.
- The function returns the retrieved user data.
6.3 Using then() and catch()
axios
.get('https://jsonplaceholder.typicode.com/users')
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error('Request failed:', error.message);
});
Promises can be handled with either then() and catch() or async/await with try/catch. Choose the style that makes the application's asynchronous logic easiest to understand.
7. Displaying API Data in React Native
After retrieving data with Axios, a component can store it in state and display it using React Native components.
7.1 Example Using useState and useEffect
import React, { useEffect, useState } from 'react';
import {
ActivityIndicator,
FlatList,
Text,
View,
} from 'react-native';
import axios from 'axios';
export default function UsersScreen() {
const [users, setUsers] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
async function loadUsers() {
try {
const response = await axios.get(
'https://jsonplaceholder.typicode.com/users'
);
setUsers(response.data);
} catch (err) {
setError('Unable to load users.');
} finally {
setLoading(false);
}
}
loadUsers();
}, []);
if (loading) {
return (
<View>
<ActivityIndicator size="large" />
<Text>Loading users...</Text>
</View>
);
}
if (error) {
return <Text>{error}</Text>;
}
if (users.length === 0) {
return <Text>No users found.</Text>;
}
return (
<FlatList
data={users}
keyExtractor={item => String(item.id)}
renderItem={({ item }) => (
<View>
<Text>{item.name}</Text>
<Text>{item.email}</Text>
</View>
)}
/>
);
}
7.2 How This Example Works
- The component initializes the users, loading, and error states.
- The effect starts the API request when the component mounts.
- Axios retrieves the user data.
- The component stores the returned array in state.
- If the request fails, the component sets an error message.
- The finally block turns off the loading state.
- The component renders a spinner, error message, empty state, or list as appropriate.
For production screens, consider request cancellation, retry controls, and preserving previously loaded data during background refreshes.
8. Making a POST Request with Axios
The POST method is commonly used to submit data to a server or request creation of a new resource.
8.1 Example POST Request
import axios from 'axios';
async function createPost() {
const response = await axios.post(
'https://jsonplaceholder.typicode.com/posts',
{
title: 'Learning Axios',
body: 'Practising HTTP requests in React Native.',
userId: 1,
}
);
return response.data;
}
Axios serializes ordinary JavaScript object request bodies as JSON and normally sets an appropriate content type. The exact request format should match the backend's API contract.
8.2 POST Request with a Submit Handler
async function handleSubmit() {
try {
setSubmitting(true);
setError(null);
const response = await axios.post(
'https://api.example.com/v1/contact',
{
name,
email,
message,
}
);
console.log('Submission successful:', response.data);
} catch (error) {
setError('Unable to submit the form.');
} finally {
setSubmitting(false);
}
}
This example assumes that name, email, message, and the relevant state functions are defined in the component. Validate form values before submission and handle server-side validation errors.
9. Making a PUT Request with Axios
The PUT method is commonly used to replace a resource representation. The endpoint may expect all fields required by its resource schema.
9.1 PUT Request Example
async function replaceUser() {
const response = await axios.put(
'https://api.example.com/v1/users/5',
{
name: 'Aarav Sharma',
email: '[email protected]',
phone: '9876543210',
}
);
return response.data;
}
Replace the example URL with an endpoint supported by your backend. If the API returns a 204 No Content response, do not assume that response.data contains a resource representation.
10. Making a PATCH Request with Axios
The PATCH method is used to request a partial update. It is useful when only selected fields need to be changed.
10.1 PATCH Request Example
async function updateUserName(userId, name) {
const response = await axios.patch(
`https://api.example.com/v1/users/${userId}`,
{ name }
);
return response.data;
}
This request sends only the name field. The server must support the endpoint and the chosen patch format.
11. Making a DELETE Request with Axios
The DELETE method requests the removal of a resource.
11.1 DELETE Request Example
async function deleteProduct(productId) {
const response = await axios.delete(
`https://api.example.com/v1/products/${productId}`
);
return response.status;
}
Axios can treat a 204 No Content response as a successful request. Do not attempt to parse a response body unless the API actually returns one.
12. HTTP Methods Supported by Axios
| Method |
Axios Function |
Typical Purpose |
| GET |
axios.get() |
Retrieve information. |
| POST |
axios.post() |
Submit data or create a resource. |
| PUT |
axios.put() |
Replace a resource representation. |
| PATCH |
axios.patch() |
Apply partial changes. |
| DELETE |
axios.delete() |
Request resource deletion. |
| HEAD |
axios.head() |
Retrieve response headers without a response body. |
| OPTIONS |
axios.options() |
Request information about communication options. |
13. Passing Query Parameters
Query parameters are used to filter, search, sort, or paginate API results. Axios supports the params configuration property for this purpose.
13.1 GET Request with Parameters
const response = await axios.get(
'https://jsonplaceholder.typicode.com/posts',
{
params: {
userId: 1,
_limit: 5,
},
}
);
console.log(response.data);
Axios serializes the parameters into the URL query string. The example endpoint supports demonstration queries, but the available parameters depend on the API.
13.2 Example URL
https://api.example.com/v1/products?category=electronics&page=2&limit=10
Using the params configuration is usually clearer and safer than manually concatenating query strings, especially when values contain spaces or special characters.
14. Sending HTTP Headers
HTTP headers provide additional information about a request. They may describe the expected response format, the request body format, or the credentials used to access a protected endpoint.
14.1 Common Headers
| Header |
Purpose |
Accept |
Indicates the response formats the client can accept. |
Content-Type |
Describes the format of the request body. |
Authorization |
Carries credentials or a token using the API's required scheme. |
Cache-Control |
Provides caching directives. |
14.2 Adding Headers to a Request
const response = await axios.get(
'https://api.example.com/v1/profile',
{
headers: {
Accept: 'application/json',
Authorization: `Bearer ${accessToken}`,
},
}
);
The accessToken variable must be supplied by a legitimate authentication flow. Do not hardcode actual tokens, passwords, or private API credentials in application source code.
15. Understanding Axios Error Handling
Axios rejects a request Promise by default when the response status falls outside its configured successful status range, which is commonly 2xx. It can also reject for network failures, timeouts, cancellation, or request configuration errors.
15.1 Basic Error Handling
try {
const response = await axios.get(
'https://api.example.com/v1/products'
);
setProducts(response.data);
} catch (error) {
console.error('API request failed:', error.message);
}
15.2 Understanding Axios Error Properties
| Property |
Meaning |
error.response |
The server returned a response outside the configured successful status range. |
error.request |
A request was created, but no usable response was received. |
error.message |
A message describing the error. |
error.code |
An Axios error code, when available. |
error.config |
The request configuration associated with the error. |
15.3 Handling Different Error Types
try {
const response = await axios.get(
'https://api.example.com/v1/products'
);
setProducts(response.data);
} catch (error) {
if (error.response) {
setError(
`Server returned status ${error.response.status}.`
);
} else if (error.request) {
setError('No response received. Check your connection.');
} else {
setError('Unable to prepare the request.');
}
}
Use simple, user-friendly messages in the interface. Detailed diagnostics should be handled carefully and should not expose credentials or sensitive information.
16. Loading, Success, Empty, and Error States
When an application fetches data with Axios, it should show an appropriate interface for every stage of the request.
| State |
Recommended UI |
| Loading |
Show an ActivityIndicator or placeholder. |
| Success |
Display the retrieved information. |
| Empty |
Explain that no records are available. |
| Error |
Display a helpful message and a Retry action when appropriate. |
| Refreshing |
Keep existing content visible and show a refresh indicator. |
16.1 Example State Variables
const [products, setProducts] = useState([]);
const [loading, setLoading] = useState(true);
const [refreshing, setRefreshing] = useState(false);
const [error, setError] = useState(null);
These state variables allow the component to distinguish between an initial request, a background refresh, a successful response, and a failed request.
17. Creating an Axios Instance
An Axios instance is a reusable client with common configuration. It is useful when many screens communicate with the same backend API.
17.1 Why Use an Axios Instance?
- Share a common base URL.
- Configure default headers.
- Set a consistent timeout.
- Register request and response interceptors.
- Keep API configuration separate from UI components.
- Make networking code easier to maintain and test.
17.2 Creating an API Client
// src/api/apiClient.js
import axios from 'axios';
const apiClient = axios.create({
baseURL: 'https://api.example.com/v1',
timeout: 10000,
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
});
export default apiClient;
Replace the placeholder base URL with the URL supplied by your backend. The timeout is expressed in milliseconds; this example sets a ten-second timeout.
17.3 Using the Axios Instance
import apiClient from './api/apiClient';
async function getProducts() {
const response = await apiClient.get('/products');
return response.data;
}
Because the instance has a base URL, the request path can be supplied as /products instead of repeating the entire URL.
18. Request Interceptors
A request interceptor runs before a request is sent. It can be used to attach authorization headers, add common metadata, or apply shared request configuration.
18.1 Basic Request Interceptor
apiClient.interceptors.request.use(
config => {
console.log(
'Sending request:',
config.method,
config.url
);
return config;
},
error => Promise.reject(error)
);
The interceptor must return the updated configuration so that the request can proceed. Avoid logging tokens, passwords, or sensitive request bodies.
18.2 Adding an Authorization Token
apiClient.interceptors.request.use(
async config => {
const token = await getAccessToken();
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
},
error => Promise.reject(error)
);
getAccessToken() represents an application function that retrieves a valid token from the appropriate authentication or secure-storage layer. It must be implemented separately.
Interceptors should be registered in a shared API module rather than repeatedly inside components. If an interceptor is registered inside a component effect, clean it up when the effect ends to avoid accumulating duplicate handlers.
19. Response Interceptors
A response interceptor runs before the result is delivered to the calling code. It can be used to normalize responses, centralize error reporting, or implement carefully designed authentication workflows.
19.1 Basic Response Interceptor
apiClient.interceptors.response.use(
response => response,
error => {
if (error.response?.status === 401) {
// Notify the authentication layer.
}
return Promise.reject(error);
}
);
The rejected error is passed back to the caller so that individual screens can still handle errors appropriately.
19.2 Important Interceptor Practices
- Keep request and response behavior consistent.
- Return the response or reject the error deliberately.
- Avoid hiding errors that components need to handle.
- Do not log sensitive credentials or private response data.
- Avoid creating infinite retry loops in authentication handlers.
- Remove dynamically registered interceptors when they are no longer needed.
20. Configuring Request Timeouts
A timeout limits how long Axios waits for a request before treating it as failed. Without an appropriate timeout, a slow or unresponsive endpoint may leave the user waiting longer than expected.
20.1 Timeout in an Axios Instance
const apiClient = axios.create({
baseURL: 'https://api.example.com/v1',
timeout: 10000,
});
20.2 Timeout for an Individual Request
const response = await axios.get(
'https://api.example.com/v1/reports',
{
timeout: 15000,
}
);
Timeout values should reflect the operation. A small request may need a shorter timeout than a report-generation endpoint. Handle timeout errors gracefully and retry only when doing so is appropriate.
21. Cancelling Axios Requests
A request may become unnecessary when the user navigates away from a screen or changes a search query. Axios supports request cancellation with AbortController in current versions.
21.1 Using AbortController
import axios from 'axios';
import { useEffect, useState } from 'react';
function ProductsScreen() {
const [products, setProducts] = useState([]);
const [error, setError] = useState(null);
useEffect(() => {
const controller = new AbortController();
async function loadProducts() {
try {
const response = await axios.get(
'https://jsonplaceholder.typicode.com/posts',
{
signal: controller.signal,
}
);
setProducts(response.data);
} catch (err) {
if (!controller.signal.aborted) {
setError('Unable to load products.');
}
}
}
loadProducts();
return () => {
controller.abort();
};
}, []);
return null;
}
This example illustrates cancellation and omits the screen's presentation markup. In a complete component, render the products, loading state, and error state. Replace the demonstration endpoint with a products endpoint if the response should contain products.
21.2 Why Cancellation Matters
- It prevents unnecessary network work when a request is no longer needed.
- It reduces the chance of stale responses updating the interface.
- It improves behavior when users change screens quickly.
- It is useful for search requests and rapidly changing parameters.
22. Organizing API Services
Separating API functions from screen components keeps an application easier to understand, test, and maintain.
22.1 Suggested Project Structure
src/
api/
apiClient.js
productsApi.js
usersApi.js
components/
LoadingView.js
ErrorView.js
ProductCard.js
screens/
ProductsScreen.js
UsersScreen.js
hooks/
useProducts.js
22.2 Products API Service
// src/api/productsApi.js
import apiClient from './apiClient';
export async function fetchProducts() {
const response = await apiClient.get('/products');
return response.data;
}
export async function createProduct(product) {
const response = await apiClient.post('/products', product);
return response.data;
}
export async function updateProduct(id, product) {
const response = await apiClient.patch(
`/products/${id}`,
product
);
return response.data;
}
export async function deleteProduct(id) {
const response = await apiClient.delete(`/products/${id}`);
return response.status;
}
These functions assume that the backend supports the listed routes and methods. Modify the paths and request bodies to match the actual API contract.
23. Axios vs Fetch API
Both Axios and Fetch can be used to make HTTP requests in React Native. The best choice depends on project requirements and the desired networking architecture.
| Feature |
Axios |
Fetch |
| Installation |
Requires the Axios package. |
Built into supported React Native environments. |
| JSON response |
Usually available in response.data. |
Call response.json(). |
| HTTP errors |
Rejects by default for status codes outside the configured successful range. |
Normally resolves even for HTTP 404 or 500 responses; check response.ok. |
| Timeout configuration |
Supports a timeout option. |
Usually implemented using AbortController or another timeout strategy. |
| Interceptors |
Provides request and response interceptors. |
No built-in interceptor system. |
| Shared client configuration |
Supports reusable Axios instances. |
Can be organized through custom helper functions. |
| Request cancellation |
Supports AbortController signals in current versions. |
Supports AbortController in compatible environments. |
Axios is useful when an application needs centralized configuration, interceptors, or a consistent request-handling pattern. Fetch is a good option when a project prefers a built-in API and minimal dependencies.
24. Common Mistakes When Using Axios
| Mistake |
Why It Happens |
Solution |
| Reading the wrong response property. |
The developer expects the response body directly. |
Use response.data for the body. |
| Not handling rejected Promises. |
The request may fail without a suitable catch handler. |
Use try/catch or catch() for failures. |
| Incorrect base URL. |
The instance points to the wrong server or API version. |
Verify the base URL and endpoint paths. |
| Incorrect request body. |
The payload does not match the server's schema. |
Inspect the API documentation and validate fields. |
| Repeated interceptor registration. |
Interceptors are added every time a component renders or mounts. |
Register shared interceptors once or eject them during cleanup. |
| Loading indicator never stops. |
Loading state is not reset after an error. |
Reset loading in a finally block. |
| Raw server error shown to users. |
Technical error details are displayed directly. |
Display a safe, understandable message. |
| Request waits too long. |
No appropriate timeout is configured. |
Set a suitable timeout and handle the error. |
| Old response replaces new results. |
Requests complete in a different order from when they started. |
Cancel outdated requests or verify which request is current. |
| Unexpected JSON parsing assumptions. |
The code expects a JSON body from every successful response. |
Handle bodyless responses such as 204 where applicable. |
25. Security Best Practices
Using Axios correctly also requires protecting application data and handling authentication carefully.
- Use HTTPS for production API requests.
- Never hardcode passwords, private API keys, or real access tokens in source code.
- Use suitable secure storage for authentication credentials.
- Validate important input on both the client and the server.
- Enforce permissions on the backend instead of trusting the mobile client.
- Do not log tokens, passwords, or sensitive personal information.
- Handle expired sessions and 401 responses through the authentication layer.
- Do not automatically retry operations that may create duplicate records or payments unless the API supports safe idempotency mechanisms.
- Keep error messages informative without exposing internal implementation details.
26. Performance Best Practices
- Use a shared Axios instance for common API configuration.
- Retrieve only the information required by the screen.
- Use pagination for large datasets.
- Cancel requests that are no longer needed.
- Use caching or a server-state library when suitable.
- Avoid repeated requests caused by incorrect effect dependencies.
- Use loading indicators that match the type of request.
- Preserve existing content during background refreshes where appropriate.
- Keep networking logic outside large UI components when that improves maintainability.
- Test the application on real devices and different network conditions.
27. Practical Project: Product Listing Application Using Axios
Project Objective: Build a React Native application that retrieves products from an API and supports basic product operations using Axios.
27.1 Project Features
- Retrieve products using GET.
- Display product names, prices, and descriptions.
- Show a loading indicator during the initial request.
- Display an error message when a request fails.
- Provide a Retry button.
- Create a product using POST.
- Update product information using PUT or PATCH as supported by the API.
- Delete a product using DELETE.
- Use a shared Axios instance.
- Refresh the product list after successful changes.
27.2 Example Product Service
// src/api/productsApi.js
import apiClient from './apiClient';
export const getProducts = async () => {
const response = await apiClient.get('/products');
return response.data;
};
export const addProduct = async product => {
const response = await apiClient.post('/products', product);
return response.data;
};
export const editProduct = async (id, updates) => {
const response = await apiClient.patch(
`/products/${id}`,
updates
);
return response.data;
};
export const removeProduct = async id => {
const response = await apiClient.delete(`/products/${id}`);
return response.status;
};
27.3 Development Steps
- Create a React Native project.
- Install Axios using npm or Yarn.
- Create a shared Axios instance with the backend base URL.
- Create product service functions for the supported endpoints.
- Fetch products and store them in React state.
- Display the results using FlatList.
- Add loading, empty, error, and retry states.
- Build a form to create a product.
- Implement the supported update and delete operations.
- Test valid requests, invalid data, HTTP errors, and offline behavior.
27.4 Expected Outcome
The application should retrieve and display product information, provide appropriate feedback during network operations, and support the operations permitted by the backend. All API paths, fields, and HTTP methods must match the actual server implementation.
28. Practice Exercises
- Install Axios in a React Native project.
- Fetch a list of users and print the returned data.
- Display the retrieved users using FlatList.
- Implement a POST request to submit a form.
- Use PATCH to update a single field of a resource.
- Implement a DELETE request and update the UI after success.
- Pass search and pagination parameters using Axios.
- Create a shared Axios instance with a base URL and timeout.
- Add a request interceptor that attaches an authorization token.
- Add a response interceptor that identifies 401 errors.
- Implement cancellation using AbortController.
- Display different messages for HTTP errors and network failures.
29. Interview Questions and Answers
Q1. What is Axios?
Axios is a Promise-based HTTP client library used to send requests and receive responses from APIs.
Q2. Why is Axios used in React Native?
It simplifies HTTP communication and provides features such as request configuration, automatic response transformation, interceptors, timeouts, and centralized API instances.
Q3. How do you install Axios?
Run npm install axios or yarn add axios in the project directory.
Q4. What does axios.get() do?
It sends a GET request to retrieve information from an API endpoint.
Q5. What is response.data?
It contains the response body, commonly parsed into a JavaScript object or array.
Q6. What is the difference between axios.post() and axios.put()?
POST submits data for processing or resource creation, while PUT commonly replaces a resource representation. The endpoint contract determines the exact behavior.
Q7. What is an Axios instance?
An Axios instance is a reusable client with shared configuration such as base URL, timeout, and headers.
Q8. What is an interceptor?
An interceptor processes a request before it is sent or processes a response before it reaches the calling code.
Q9. How do you handle errors in Axios?
Use try/catch with async/await or a Promise catch handler, and inspect the available error properties to distinguish HTTP errors, network failures, and setup problems.
Q10. How can you add an authorization token?
Include the token in the appropriate Authorization header, either on a specific request or through a configured instance or request interceptor.
Q11. How do you set a timeout in Axios?
Set the timeout option in milliseconds on an individual request or an Axios instance.
Q12. How can you cancel an Axios request?
Use an AbortController and pass its signal in the request configuration, then call abort() when the request is no longer needed.
Q13. Does Axios automatically parse JSON?
Axios normally transforms JSON response bodies into JavaScript values, making them available through response.data.
Q14. What is the difference between Axios and Fetch?
Axios offers features such as interceptors, instance configuration, and convenient HTTP error handling. Fetch is built into supported React Native environments but requires explicit response status checks for HTTP errors.
Q15. Why should interceptors not be registered repeatedly?
Repeated registration can cause the same processing logic to run multiple times, leading to duplicate headers, repeated logging, or other unexpected behavior.
Q16. What is the purpose of an Axios timeout?
A timeout limits how long the client waits for a request before treating it as failed.
Q17. What is the difference between error.response and error.request?
error.response indicates that a server response was received but rejected under the configured status rules. error.request generally indicates that a request was made but no usable response was received.
Q18. Why should API logic be separated from UI components?
Separating API logic improves reuse, readability, testability, and maintenance.
30. Quick Revision Notes
- Axios: Promise-based HTTP client library.
- Installation:
npm install axios.
- GET:
axios.get().
- POST:
axios.post().
- PUT:
axios.put().
- PATCH:
axios.patch().
- DELETE:
axios.delete().
- Response body:
response.data.
- Status code:
response.status.
- Query parameters: The
params configuration property.
- Request headers: The
headers configuration property.
- Axios instance: A reusable client created with
axios.create().
- Request interceptor: Processes a request before it is sent.
- Response interceptor: Processes a response before it reaches the caller.
- Timeout: Limits how long a request can wait.
- Cancellation: Use AbortController with the request signal.
- Error handling: Use try/catch or catch() and provide useful feedback.
31. Conclusion
Axios is a useful tool for implementing HTTP communication in React Native applications. It simplifies API requests, provides a consistent response structure, supports shared configuration, and offers interceptors for common request and response processing.
Start by learning GET and POST requests, then practise PUT, PATCH, and DELETE. Next, create a reusable Axios instance, manage loading and error states, configure request headers, and learn how to use interceptors and cancellation safely.
For further learning, explore the React Native Training Course, register through the JustAcademy course demo page, and visit the JustAcademy website.
32. Additional Learning Resources