React Fetching Data Using Fetch Api And Axios Complete Guide
Understanding the Core Concepts of React Fetching Data using Fetch API and Axios
React Fetching Data: Fetch API vs. Axios
Fetch API
Overview:
The Fetch API is a modern interface that allows developers to make web requests to servers from web browsers. It’s a built-in JavaScript API and works natively in most modern browsers. The Fetch API provides a global fetch()
method that can be used to make requests to APIs.
Features:
Promises:
- Fetch uses Promises, which makes it easier to work with asynchronous operations by chaining
then()
methods. fetch(url, options).then(response => response.json()).then(data => console.log(data)).catch(error => console.error(error));
- Fetch uses Promises, which makes it easier to work with asynchronous operations by chaining
Readability:
- Fetch API is clean and easy to read, making it a good choice for beginners.
Request Options:
- You can specify request options such as method (GET, POST, etc.), headers, and body content.
fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data) })
No Dependencies:
- Being a built-in API, Fetch requires no additional installation, which helps keep your project lightweight.
Limitations:
No Timeout Support:
- Fetch does not have built-in support for request timeouts, so you have to implement it using JavaScript.
No Automatic JSON Parsing:
- Fetch does not automatically parse the response data as JSON, so you need to call
response.json()
explicitly.
- Fetch does not automatically parse the response data as JSON, so you need to call
Error Handling:
- The HTTP error status codes (e.g., 404, 500) are not treated as errors by default in Fetch API. You need to explicitly check for these in the response.
Axios
Overview:
Axios is a popular third-party library for making HTTP requests in React and other JavaScript frameworks. It is promise-based and provides a convenient API for making network requests.
Features:
Automatic JSON Parsing:
- Axios automatically converts response data to JSON, eliminating the need to call
response.json()
.
- Axios automatically converts response data to JSON, eliminating the need to call
Timeout Support:
- Axios has built-in support for request timeouts, making it easier to handle scenarios where a server is unresponsive.
Interceptors:
- Axios allows you to intercept requests and responses globally. This is useful for adding authentication headers or handling errors consistently.
Request and Response Transform:
- You can customize request and response transformations, which can be handy for pre-processing data before sending or after receiving it.
Error Handling:
- Axios treats HTTP error status codes as errors, which makes it easier to handle them consistently.
Installation:
npm install axios
Usage Example:
import axios from 'axios';
axios.get('https://api.example.com/data')
.then(response => console.log(response.data))
.catch(error => console.error(error));
axios.post('https://api.example.com/data', { key: 'value' })
.then(response => console.log(response.data))
.catch(error => console.error(error));
Choosing Between Fetch API and Axios
When to Use Fetch API:
- When you want to keep your project lightweight and avoid adding extra dependencies.
- When working in environments that support Fetch (modern browsers and some server-side environments).
- When you prefer a native, standard-based API with minimal overhead.
When to Use Axios:
- When you need automatic JSON parsing for responses.
- When you require built-in support for request timeouts.
- When you want to leverage interceptors for consistent request and response handling.
- When you’re working in environments that may not support Fetch (e.g., older browsers).
Conclusion
Online Code run
Step-by-Step Guide: How to Implement React Fetching Data using Fetch API and Axios
Prerequisites:
- Basic understanding of JavaScript and React.
- Node.js and npm installed on your machine.
- Create-React-App installed globally.
Step-by-Step Guide:
Step 1: Set up a React project
First, create a new React project using Create-React-App:
npx create-react-app react-fetch-example
cd react-fetch-example
Step 2: Install Axios
We need to install the Axios library to use it in our application:
npm install axios
Step 3: Clean up the example project
Navigate to the src
folder and clean up the default App.js
file. Remove unnecessary code and leave only the following:
// src/App.js
import React from 'react';
import './App.css';
function App() {
return (
<div className="App">
<header className="App-header">
<h1>React Fetching Data Example</h1>
</header>
</div>
);
}
export default App;
Step 4: Example using Fetch API
Let's start with the Fetch API. We'll create a component called FetchData.js
and fetch data from a public API.
- Create a component
FetchData.js
:
// src/FetchData.js
import React, { useState, useEffect } from 'react';
const FetchData = () => {
const [data, setData] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
fetch("https://jsonplaceholder.typicode.com/posts")
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data => {
setData(data);
setLoading(false);
})
.catch(error => {
setError(error);
setLoading(false);
});
}, []);
if (loading) return <div>Loading...</div>;
if (error) return <div>Error: {error.message}</div>;
return (
<div>
<h2>Data fetched using Fetch API</h2>
<ul>
{data.map(post => (
<li key={post.id}>{post.title}</li>
))}
</ul>
</div>
);
};
export default FetchData;
- Import and use the
FetchData
component inApp.js
:
// src/App.js
import React from 'react';
import FetchData from './FetchData';
import './App.css';
function App() {
return (
<div className="App">
<header className="App-header">
<h1>React Fetching Data Example</h1>
<FetchData />
</header>
</div>
);
}
export default App;
Step 5: Example using Axios
Now, let's create a component called AxiosData.js
and fetch data using Axios.
- Create a component
AxiosData.js
:
// src/AxiosData.js
import React, { useState, useEffect } from 'react';
import axios from 'axios';
const AxiosData = () => {
const [data, setData] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
axios.get("https://jsonplaceholder.typicode.com/posts")
.then(response => {
setData(response.data);
setLoading(false);
})
.catch(error => {
setError(error);
setLoading(false);
});
}, []);
if (loading) return <div>Loading...</div>;
if (error) return <div>Error: {error.message}</div>;
return (
<div>
<h2>Data fetched using Axios</h2>
<ul>
{data.map(post => (
<li key={post.id}>{post.title}</li>
))}
</ul>
</div>
);
};
export default AxiosData;
- Import and use the
AxiosData
component inApp.js
:
// src/App.js
import React from 'react';
import FetchData from './FetchData';
import AxiosData from './AxiosData';
import './App.css';
function App() {
return (
<div className="App">
<header className="App-header">
<h1>React Fetching Data Example</h1>
<FetchData />
<AxiosData />
</header>
</div>
);
}
export default App;
Step 6: Run the application
Now, you can start your application and see the components in action:
npm start
Open your browser and navigate to http://localhost:3000
. You should see the titles of posts fetched from the JSONPlaceholder API using both the Fetch API and Axios.
Summary:
- The Fetch API is built into modern browsers and allows you to make network requests without needing any additional library.
- Axios is a third-party library that makes it easier to make HTTP requests with a cleaner syntax and more features compared to Fetch API.
Top 10 Interview Questions & Answers on React Fetching Data using Fetch API and Axios
1. What is the difference between Fetch API and Axios in React?
Fetch API: It's a built-in JavaScript API provided by modern browsers to make network requests. It returns promises and uses the fetch()
function which can be utilized for sending HTTP or HTTPS requests.
Axios: A popular third-party library for making HTTP requests from node.js or XMLHttpRequests from the browser. It supports Promises, which makes it easy to use in React applications. Unlike Fetch API, Axios automatically transforms JSON data.
2. How do I use the Fetch API to get data from an external JSON API in React?
import { useState, useEffect } from 'react';
function FetchData() {
const [data, setData] = useState([]);
useEffect(() => {
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => setData(data))
.catch(error => console.error('Error fetching data:', error));
}, []);
return (
<div>
{/* Render your data here */}
{data.map(item =>
<div key={item.id}>{item.name}</div>
)}
</div>
);
}
export default FetchData;
Here, you're using the useEffect
hook to trigger a fetch request after the component mounts, and the useState
hook to store the fetched data.
3. Can I use Axios in React instead of the Fetch API? How?
First, install Axios:
npm install axios
Then, you can fetch data using Axios as follows:
import React, { useState, useEffect } from 'react';
import axios from 'axios';
function FetchAxiosData() {
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>
{/* Render your data here */}
{data.map(item =>
<div key={item.id}>{item.name}</div>
)}
</div>
);
}
export default FetchAxiosData;
The get()
method in Axios automatically parses JSON from the responses.
4. When should I use Fetch API and when should I consider Axios?
Use Fetch API when:
- You are working with a modern browser and prefer using native JavaScript functionality.
- You want to have fine-grained control of the request process.
Consider Axios when:
- You need more features such as automatic JSON transformation, built-in support for canceling requests, and request and response interceptors.
- You want cleaner code and better handling of cross-browser compatibility since Axios manages it internally.
5. How do I handle errors more gracefully using Axios in React?
Axios has a catch
method that catches all network errors or HTTP error responses (status codes 4xx and 5xx).
import React, { useState, useEffect } from 'react';
import axios from 'axios';
const FetchErrorHandlingData = () => {
const [error, setError] = useState(null);
const [data, setData] = useState([]);
useEffect(() => {
axios.get('https://api.example.com/data')
.then((response) => setData(response.data))
.catch((err) => {
// Network error
if (!err.response) {
setError("Network Error");
} else {
// HTTP error
setError(err.response.status + ": " + err.response.statusText);
}
});
}, []);
// Render logic
}
export default FetchErrorHandlingData;
6. How can I add headers to my Axios request?
Pass the headers object as the second argument within a config
object in your request:
axios.get('/your-url-here', {
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer YOUR_ACCESS_TOKEN'
}
})
.then(response => ...)
.catch(error => ...);
7. How can I make POST requests using both the Fetch API and Axios?
Using Fetch API:
fetch('https://api.example.com/data', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
title: 'foo',
body: 'bar',
userId: 1
})
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
Using Axios:
axios.post('https://api.example.com/data', {
title: 'foo',
body: 'bar',
userId: 1
})
.then(response => console.log(response.data))
.catch(error => console.error('Error:', error));
Axios automatically converts the data to JSON.
8. Is there a way to add timeouts in network requests when using either Fetch API or Axios?
Fetch API: Fetch does not support timeout natively, but you can combine fetch with a promise-based timeout solution like so:
const fetchDataWithTimeout = async (url, ms) => {
const controller = new AbortController();
const signal = controller.signal;
setTimeout(() => controller.abort(), ms);
try {
let response = await fetch(url, { signal });
let data = await response.json();
console.log(data);
} catch (err) {
if (err.name === 'AbortError') {
console.log('Timeout');
}
}
};
fetchDataWithTimeout('https://api.example.com/data', 5000); // timeout after 5 seconds
Axios:
Axios provides a built-in timeout
configuration option:
axios.get('https://api.example.com/data', {
timeout: 5000 // timeout after 5 seconds
})
.then(response => console.log(response.data))
.catch(error => {
if (error.code === "ECONNABORTED") {
console.log('Timeout');
}
});
9. How can I perform async/await syntax while fetching using the Fetch API and Axios in React?
Fetch API with async/await:
import { useState, useEffect } from 'react';
function FetchAsyncData() {
const [data, setData] = useState([]);
useEffect(() => {
async function getData() {
try {
const response = await fetch('https://api.example.com/data');
const result = await response.json();
setData(result);
} catch (err) {
console.error('Error:', err);
}
}
getData(); // Invoke immediately
}, []);
// render logic
}
Axios with async/await:
import React, { useState, useEffect } from 'react';
import axios from 'axios';
const FetchAxiosAsyncData = () => {
const [data, setData] = useState([]);
useEffect(() => {
const getData = async () => {
try {
const response = await axios.get('https://api.example.com/data');
setData(response.data);
} catch (error) {
console.error("Error:", error);
}
};
getData(); // Invoke immediately
}, []);
// render logic
}
export default FetchAxiosAsyncData;
10. Is there any advantage in using one over the other (Fetch vs Axios) for fetching data in React?
While the Fetch API is native and lightweight, Axios offers several advantages:
- Easier to work with, especially for handling JSON data since it parses it automatically.
- Comprehensive error handling that differentiates network errors and HTTP errors.
- Ability to configure defaults and create reusable instances.
- Built-in support for request cancellation, which can prevent memory leaks.
- Interceptors to allow modifying or observing requests globally.
However, if you're looking for a pure JavaScript solution with no external dependencies or need advanced control over requests, the Fetch API might be more appropriate. For most cases, Axios simplifies the process of data fetching in React applications.
Login to post a comment.