10 React Axios Interview Questions and Answers
Prepare for your interview with our guide on React Axios, covering key concepts and practical insights to enhance your understanding and skills.
Prepare for your interview with our guide on React Axios, covering key concepts and practical insights to enhance your understanding and skills.
React Axios is a powerful combination for building dynamic web applications. React, a popular JavaScript library for building user interfaces, pairs seamlessly with Axios, a promise-based HTTP client, to handle asynchronous data fetching and state management. This integration allows developers to create responsive and efficient applications that can interact with APIs and handle real-time data updates with ease.
This article provides a curated selection of interview questions focused on React Axios. By working through these questions and their detailed answers, you will gain a deeper understanding of how to effectively use React Axios in your projects, enhancing your readiness for technical interviews and boosting your confidence in discussing these technologies.
To perform a basic GET request using Axios in a React component, follow these steps:
Here’s an example using a functional component with the useEffect hook:
import React, { useState, useEffect } from 'react'; import axios from 'axios'; const DataFetchingComponent = () => { const [data, setData] = useState([]); useEffect(() => { axios.get('https://api.example.com/data') .then(response => { setData(response.data); }) .catch(error => { console.error('Error fetching data:', error); }); }, []); return ( <div> <h1>Fetched Data</h1> <ul> {data.map(item => ( <li key={item.id}>{item.name}</li> ))} </ul> </div> ); }; export default DataFetchingComponent;
In Axios, errors can be handled using the .catch
method for promises or try...catch
blocks with async/await syntax. Axios provides detailed error objects that include information such as the HTTP status code, error message, and request configuration.
Example using promises:
axios.get('/api/data') .then(response => { console.log(response.data); }) .catch(error => { if (error.response) { console.error('Server Error:', error.response.status); } else if (error.request) { console.error('Network Error:', error.request); } else { console.error('Error:', error.message); } });
Example using async/await:
async function fetchData() { try { const response = await axios.get('/api/data'); console.log(response.data); } catch (error) { if (error.response) { console.error('Server Error:', error.response.status); } else if (error.request) { console.error('Network Error:', error.request); } else { console.error('Error:', error.message); } } } fetchData();
To make a POST request using Axios, you need to first install Axios if it is not already included in your project. Axios is a promise-based HTTP client for the browser and Node.js.
Here is an example of how to use Axios to send JSON data in a POST request:
import React, { useState } from 'react'; import axios from 'axios'; const PostRequestExample = () => { const [response, setResponse] = useState(null); const sendPostRequest = async () => { try { const res = await axios.post('https://example.com/api/data', { key1: 'value1', key2: 'value2' }); setResponse(res.data); } catch (error) { console.error('Error making POST request:', error); } }; return ( <div> <button onClick={sendPostRequest}>Send POST Request</button> {response && <div>Response: {JSON.stringify(response)}</div>} </div> ); }; export default PostRequestExample;
In Axios, setting default headers is useful when you need to include common headers, such as authentication tokens, in all your HTTP requests. This can be done by configuring Axios to use default headers globally or for specific instances.
Example:
import axios from 'axios'; // Setting default headers globally axios.defaults.headers.common['Authorization'] = 'Bearer YOUR_TOKEN_HERE'; // Creating an Axios instance with default headers const apiClient = axios.create({ baseURL: 'https://api.example.com', headers: { 'Authorization': 'Bearer YOUR_TOKEN_HERE', 'Content-Type': 'application/json' } }); // Using the Axios instance to make a request apiClient.get('/endpoint') .then(response => { console.log(response.data); }) .catch(error => { console.error(error); });
Interceptors in Axios are functions that Axios calls for every request or response. They allow you to modify the request or response before it is handled by the then or catch methods. There are two types of interceptors: request interceptors and response interceptors.
A common use case for interceptors is to add an authentication token to every request. This ensures that all requests to the server are authenticated without having to manually add the token to each request.
Example:
import axios from 'axios'; // Create an instance of Axios const axiosInstance = axios.create(); // Add a request interceptor axiosInstance.interceptors.request.use( function (config) { const token = localStorage.getItem('authToken'); if (token) { config.headers.Authorization = `Bearer ${token}`; } return config; }, function (error) { return Promise.reject(error); } ); // Add a response interceptor axiosInstance.interceptors.response.use( function (response) { return response; }, function (error) { if (error.response.status === 401) { console.log('Unauthorized, logging out...'); } return Promise.reject(error); } ); // Example request using the axios instance axiosInstance.get('/user') .then(response => { console.log(response.data); }) .catch(error => { console.error(error); });
Axios interceptors allow you to run your code or modify the request/response before the request is sent or after the response is received. This can be useful for retrying failed requests.
Here is a code snippet that demonstrates how to use Axios interceptors to retry a failed request:
import axios from 'axios'; const axiosInstance = axios.create(); axiosInstance.interceptors.response.use( response => response, async error => { const { config } = error; if (!config.__retryCount) { config.__retryCount = 0; } if (config.__retryCount < 3) { config.__retryCount += 1; return axiosInstance(config); } return Promise.reject(error); } ); // Example request axiosInstance.get('https://api.example.com/data') .then(response => console.log(response.data)) .catch(error => console.error('Request failed:', error));
Managing authentication tokens with Axios involves using interceptors to attach the token to every request. This ensures that the token is included in the headers of each HTTP request made by Axios.
Here is an example of how to set up Axios interceptors for managing authentication tokens:
import axios from 'axios'; // Create an Axios instance const axiosInstance = axios.create({ baseURL: 'https://api.example.com', }); // Add a request interceptor axiosInstance.interceptors.request.use( config => { const token = localStorage.getItem('authToken'); if (token) { config.headers['Authorization'] = `Bearer ${token}`; } return config; }, error => { return Promise.reject(error); } ); // Add a response interceptor axiosInstance.interceptors.response.use( response => { return response; }, error => { if (error.response.status === 401) { // Redirect to login page or refresh token } return Promise.reject(error); } ); export default axiosInstance;
To upload a file using Axios, you can follow these steps:
Here is an example:
import React, { useState } from 'react'; import axios from 'axios'; const FileUpload = () => { const [file, setFile] = useState(null); const handleFileChange = (e) => { setFile(e.target.files[0]); }; const handleUpload = async () => { const formData = new FormData(); formData.append('file', file); try { const response = await axios.post('/upload', formData, { headers: { 'Content-Type': 'multipart/form-data', }, }); console.log('File uploaded successfully:', response.data); } catch (error) { console.error('Error uploading file:', error); } }; return ( <div> <input type="file" onChange={handleFileChange} /> <button onClick={handleUpload}>Upload</button> </div> ); }; export default FileUpload;
In Axios, timeouts specify the maximum amount of time a request can take before being aborted. This is useful in scenarios where network latency or server issues might cause requests to hang indefinitely.
To set a timeout in Axios, use the timeout
property in the request configuration. If the request takes longer than the specified duration, Axios will throw an error.
Example:
import axios from 'axios'; const fetchData = async () => { try { const response = await axios.get('https://api.example.com/data', { timeout: 5000 // Timeout set to 5000ms (5 seconds) }); console.log(response.data); } catch (error) { if (error.code === 'ECONNABORTED') { console.error('Request timed out'); } else { console.error('An error occurred:', error.message); } } }; fetchData();
To transform request data before sending it using Axios, you can use interceptors. Interceptors allow you to modify the request before it is sent.
Here is a code snippet that demonstrates how to use an Axios interceptor to transform request data:
const axios = require('axios'); // Create an instance of Axios const instance = axios.create(); // Add a request interceptor instance.interceptors.request.use(function (config) { if (config.data) { config.data = JSON.stringify(config.data); } return config; }, function (error) { return Promise.reject(error); }); // Example request instance.post('/api/data', { key: 'value' }) .then(response => { console.log(response.data); }) .catch(error => { console.error(error); });