My self Chakrapani Upadhyaya, In this article we will look into the differences axios and fetch api.
As per my understanding, Fetch and Axios are very similar in functionality, but fetch has more backwards compatibility compare to Axios. Axios work better then fetch because fetch doesn't work in IE 11.
Here's a step-by-step example of making an API request using both Axios and Fetch in a React.js application, using the https://reqres.in/ API:
1. First, create a new React.js project and navigate to the project directory:
npx create-react-app my-app
cd my-app
2. Install Axios as a dependency for the Axios example:
npm install axios
3. In the src folder, create a new component called AxiosExample.js:
// src/AxiosExample.js import React, { useEffect, useState } from 'react'; import axios from 'axios'; const AxiosExample = () => { const [users, setUsers] = useState([]); useEffect(() => { // Make the API request using Axios axios.get('https://reqres.in/api/users') .then(response => { setUsers(response.data.data); }) .catch(error => { console.error('Error fetching data:', error); }); }, []); return ( <div> <h2>Users fetched using Axios:</h2> <ul> {users.map(user => ( <li key={user.id}>{user.first_name} {user.last_name}</li> ))} </ul> </div> ); }; export default AxiosExample;
4. In the src folder, create a new component called FetchExample.js
import React, { useEffect, useState } from "react"; const FetchExample = () => { const [users, setUsers] = useState([]); useEffect(() => { // Make the API request using Axios fetch("https://reqres.in/api/users") .then((res) => res.json()) .then((json) => { setUsers(json.data); }); }, []); return ( <div> <h2>Users fetched using Fetch:</h2> <ul> {users.map((user) => ( <li key={user.id}> {user.first_name} {user.last_name} </li> ))} </ul> </div> ); }; export default FetchExample;
5. Finally, modify the App.js component to use both examples:
// src/App.js import React from 'react'; import './App.css'; import AxiosExample from './AxiosExample'; import FetchExample from './FetchExample'; function App() { return ( <div className="App"> <AxiosExample /> <FetchExample /> </div> ); } export default App;
6. Start the development server:
npm start
Now, when you run the React app (http://localhost:3000), you should see a list of users fetched using both Axios and Fetch from the ReqRes API.
Very good article
ReplyDelete