How To Use Axios with React
Quick Summary: How do we use Axios with React? We’ve got you covered! This blog covers the best way to use react with axios. How developers can follow best practices to resolve challenges. Keep reading!!
Introduction
If you are a React developer looking to take your app to the next level, you’re at the right place.
Axios- an innovative JavaScript library. It will be a boon when it comes to HTTP requests in React. The integration of Axios with React will be good for your application.
You can intercept and cancel requests while the client side protects against cross-site request forgery.
This post will utilize Axios to access the popular JSON Placeholder API within a React project. So, read and harness this amazing combination and provide the best React.JS Solutions.
What Is Axios?
At the initial level, every API call seems simple. useEffect(), axios.get(), loading state and error handling. A developer feels all work is done. However, as an application grows, the same pattern is being repeated in every component. And maintenance becomes highly difficult. Modern Axios patterns improve the complete data fetching strategy. Basic Axios pattern is a perfect starting point for learning React. Moreover, this could be a major reason to Hire React JS Developer.
Concurrent Requests: Fetching Multiple Resources in Parallel
1. Why Sequential API Requests Slow Down Your Application
As the dashboard opens, the user profile gets loaded. Next, post request is received. Then analytics. Every request waits for another. That’s the reason the page feels slow. When independent APIs are available. Fetching API in parallel is the most efficient approach.
Sequential requests cause the following:
- Longer loading times
- Poor user experience
- Unnecessary waiting
- Slower dashboards
- Delayed rendering
2. Fetch Multiple APIs in Parallel Using Promise.all()
If APIs are not dependent on each other. Then simultaneously calling them is the best strategy. Promise.all() executes the requests at one time. And return combined results upon completion.
Common parallel requests:
- User profile
- Notifications
- Dashboard statistics
- Blog posts
- Product categories
3. Why Promise.all() Is the Preferred Solution
React developers use Promises. all() to handle multiple API calls. It provides clear syntax and saves developers from unnecessary nested requests. Codes are readable and execution becomes significantly faster.
Why use Promise.all():
- Runs requests simultaneously
- Cleaner async code
- Faster response time
- Easy result handling
- Better scalability
4. Improve Dashboard Performance with Concurrent Requests
Each API request takes 300ms to finish. The sequential execution will complete within 900 milliseconds. However, a parallel request delivers the same data in approximately 300 ms. Users can instantly perceive that the application is responsive.
Performance benefits:
- Faster dashboards
- Better perceived speed
- Lower waiting time
- Improved user experience
- Higher application responsiveness
5. Follow Clean Patterns for Better Performance
Concurrent requests do not just make the application fast. It also organized the logic behind data fetching. Managing related API calls in just a single function simplifies the future debugging and maintenance process.
Best practices:
- Group related API calls
- Keep fetching logic reusable
- Separate UI from API logic
- Avoid duplicate requests
- Cache data where possible
Axios in Functional Components: The Modern Baseline
1. Understanding the Basic Axios Pattern in React
Almost all React developers begin their initial API integration with this pattern. As the useEffect() component gets mounted, the request gets received. useState() manages loading, error and response data. This simple structure is easy for beginners. Every React project becomes the starting point.
Core building blocks:
- useEffect() for API calls
- useState() for data
- Loading state
- Error state
- Response rendering
2. Why useEffect() Is the Right Place for API Calls
When developers need to execute API requests automatically once react component renders. Then, useEffect() is the best choice. Empty dependency array ([] ensures the request runs only one time as the component mounts. This saves developers from unnecessary repeated API calls.
What useEffect() handles:
- Initial data fetching
- Side effects
- One-time execution
- Dependency management
- Component lifecycle
3. Render Different UI Based on API State
Viewing a black screen is not a good experience for the user. Display loading indicators when the request is in process. Display meaningful messages when errors are encountered. Render actual data after a successful response.
Typical rendering flow:
- Show loading indicator
- Display error message
- Render API data
- Handle empty results
- Keep UI responsive
Prerequisites
To follow along with this article, you’ll need the following items:
You are running node on your computer, version 10.16.0. For installation on macOS, follow the instructions in How to Install Node.js and Create a Local Development Environment on macOS. For installation on Ubuntu 18.04, follow the Installing Using a PPA section of How To Install Node.js on Ubuntu 18.04.
Follow the How to Set Up a React Project with Create React App guide to set up a new React project using Create React App.
A fundamental grasp of JavaScript, found in the How To Code in JavaScript course, and a basic understanding of HTML and CSS would also assist.
Procedure In Steps
Step 1 — Adding Axios To The Project
In this part, you’ll add Axios to a React project you made using the Create React App tutorial’s How to Set Up a React Project.
$ npx create-react-app react-axios-example
To add Axios to your project, open your console and navigate to the following directories:
$ cd react-axios-example
Then run this command to install Axios:
$ npm install [email protected]
Next, you will need to import Axios into the file you want to use it in.
Step 2 — Making A GET Request
To submit a GET request, you construct a new component and import Axios into it in this example.
You’ll need to make a new component called PokemonList in your React project.
First, in the src directory, make a new components subdirectory:
$ mkdir src/components
In this directory, create PokemonList.js and add the following code to the component:
import React from 'react';
import axios from 'axios';export default class PokemonList extends React.Component {
state = {
Pokemons: []
}
componentDidMount() {
axios.get(`https://pokeapi.co/api/v2/pokemon`)
.then(res => {
const pokemon= res.data;
this.setState({pokemon});
})
}
render() {
return (
<ul>
{
this.state.pokemon
.map(pokemon =>
<li key={pokemon.name}>{pokemon.name}</li>
)
}
</ul>
)
}
}
To utilize both React and Axios in the component, you must first import both. Then you conduct a GET request by hooking onto the componentDidMount lifecycle hook.
To receive a promise that yields a response object, you call axios.get(url) with a URL from an API endpoint. There is data within the response object that is then assigned the value of pokemon.
You may also receive further information about the request from res.status, such as the status code or more information from res.request.
This component should be added to your app.
import PokemonList from ‘./components/PokemonList.js’;
function App() {
return (
<div ClassName="App">
<PokemonList/>
</div>
)
}
Then run your application:
$ npm start
View the application in the browser. You will be presented with a list of names.
Step 3 — Making A POST Request
You’ll utilize Axios with another HTTP request method called POST in this stage.
You’ll need to make a new component called PokemonAdd in your React project.
To construct a form that allows for user input and then POSTs the content to an API, open PokemonAdd.js and add the following code:
import React from 'react';
import axios from 'axios';
export default class PokemonAdd extends React.Component {
state = {
name: ''
}
handleChange = event => {
this.setState({ name: event.target.value });
}
handleSubmit = event => {
event.preventDefault();
const user = {
name: this.state.name
};
axios.post(`https://pokeapi.co/api/v2/pokemon`, { name })
.then(res => {
console.log(res);
console.log(res.data);
})
}
render() {
return (
<div>
<form onSubmit={this.handleSubmit}>
<label>
Pokemon Name:
<input type="text" name="name" onChange={this.handleChange} />
</label>
<button type="submit">Add</button>
</form>
</div>
)
}
}
You override the form’s default action inside the handle submit method. Then, based on the user input, update the state.
When you use POST, you get the same response object with the same information that you may utilize in a then call.
You must first capture the user input before completing the POST request. The input is then combined with the POST request, which results in a response. Then you can console. log the response, which should show the user input in the form.
This component should be added to your app.
Js:
import PokemonAdd from './components/PokemonList';
import PokemonList from './components/PokemonAdd';
function App() {
return (
<div ClassName="App">
<PokemonAdd/>
<PokemonList/>
</div>
)
}
Then run your application:
$ npm start
Use your browser to access the application. You’ll be given a form to fill out in order to add new users. After submitting a new user, check the console.
Step 4 — Making A DELETE Request
You’ll see how to delete objects from an API using axios.delete and a URL as a parameter in this example.
You’ll need to construct a new component called PokemonRemove in your React project.
To delete a user, create PokemonRemove.js and add the following code:
import React from 'react';
import axios from 'axios';
export default class PokemonRemove extends React.Component {
state = {
id: ''
}
handleChange = event => {
this.setState({ name: event.target.value });
}
handleSubmit = event => {
event.preventDefault();
axios.delete(`https://pokeapi.co/api/v2/pokemon/${this.state.name}`)
.then(res => {
console.log(res);
console.log(res.data);
})
}
render() {
return (
<div>
<form onSubmit={this.handleSubmit}>
<label>
Pokemon Name:
<input type="text" name="name" onChange={this.handleChange} />
</label>
<button type="submit">Delete</button>
</form>
</div>
)
}
}
The res object, once again, gives information about the request. After the form is submitted, you may console.log that information again.
You should add this component.
js:
import PokemonList from './components/PokemonList';
import PokemonAdd from './components/PokemonAdd';
import PokemonRemove from './components/PokemonRemove';
function App() {
return (
<div ClassName="App">
<PokemonAdd/>
<PokemonList/>
<PokemonRemove/>
</div>
)
}
Then run your application:
$ npm start
View the application in the browser. You will be presented with a form for removing users.
Step 5 — Using A Base Instance In Axios
You’ll learn how to create a basic instance in which you may provide a URL and other configuration components in this example.
Create a new file with the name api.js:
$ nano src/api.js
Export a new axios instance with these defaults:
import axios from ‘axios’;
export default axios.create({baseURL: `https://pokeapi.co/api/v2/pokemon/`});
After you’ve built up the default instance, you may utilize it inside the PokemonRemove component. This is how you import the new instance:
import React from 'react';
import API from '../api';
export default class PokemonRemove extends React.Component {
// ...
handleSubmit = event => {
event.preventDefault();
API.delete(`pokemon/${this.state.id}`)
.then(res => {
console.log(res);
console.log(res.data);
})
}
// ...
}
Because https://pokeapi.co/api/v2/pokemon/ is now the base URL, you no longer need to type out the whole URL each time you want to hit a different endpoint on the API.
Step 6 – Using Async And Await
You’ll see how to interact with promises using async and await in this example.
The await keyword returns the value after resolving the promise. After that, the value may be assigned to a variable
import React from 'react';
import API from '../api';
export default class PokemonRemove extends React.Component {
// ...
handleSubmit = event => {
event.preventDefault();
const response = await API.delete(`pokemon/${this.state.id}`);
console.log(response);
console.log(response.data);
} // ... }
In this code sample, the .then() is replaced. The promise is resolved, and the value is stored inside the response variable.
Conclusion
Axios is not only a library, but a developer’s best friend. It also makes your work productive, keeps your code clean and ensures your app is working at its best.
Furthermore, the article you’ve read Several examples of using Axios to create HTTP requests and handle responses within a React application.
So, if you haven’t tried Axios yet, give it a shot and experience the difference it can make in your web development journey.
FAQ
Can we use Axios in the front end?
Yes, Axios can be used in the front end of web applications; nevertheless, the utilization of Axios in the front end of web applications is regularly for making API requests and not really for rendering the web application or its component views. It is a most effective library for making HTTP requests on the web browser which makes it useful for API access and asynchronous data getting in the FE world.
What is an alternative to Axios in React?
Another usage can be the built-in fetch API available in React project. fetch is a new-ish browser client, which can be used to make HTTP requests like Axios. Axios: It is used extensively in the React applications and offers a perfect solution to handling HTTP requests entirely without any third-party libraries and tools.
Does Axios use fetch internally?
Although Axios is compatible with the fetch API, it does not use it internally. Axios is a standalone, server-side JavaScript library with an integrated HTTP call method. Fetch and Axios accomplish the same thing, but Axios is more browser-compatible and allows you to use request/response interceptor features.
