How To Use Axios with React
Quick Summary: How do we use Axios with React? We’ve got you covered! This article will show you how to use Axios within your React application. We’ll provide a simple example to get you started. 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 applications.
You have to agree that many web applications will need to interact with a REST API at some point during their development. Axios is a lightweight HTTP client that is equivalent to the native JavaScript Fetch API and is based on the $http service in Angular.js v1.x.
Using JavaScript’s async and await functions enables more understandable asynchronous programming with Axios, which is based on promises.
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?
Axios is a powerful JavaScript library for making HTTP requests. In addition, It’s not just any library; it’s a game-changer for web developers. Axios simplifies the process of sending HTTP requests and handling responses. Further, clean syntax and a promise-based approach streamline data fetching from servers, making your code more elegant and efficient. Moreover, this could be a major reason to Hire React JS Developer.
Benefits of Using Axios With React
Read out the benefits of using Axios with React and begin React Staff Augmentation:
1.Ease of Use
Axios provides a straightforward API for making HTTP requests, integrating seamlessly with React. This simplicity makes it accessible to both beginners and experienced developers.
2.Promises
It uses promises, allowing you to write asynchronous code in a more readable and maintainable way, avoiding callback hell.
3.Interceptors
Axios enables you to intercept requests and responses. This feature is handy for adding headers, authentication, or global error handling.
4.Consistency
Axios ensures consistent behavior across different browsers, ensuring your React app functions reliably for all users.
5.Error Handling
It simplifies error handling. You can easily catch and manage errors, providing a more robust and user-friendly experience.
6.Concurrency
Axios supports concurrent requests, making it efficient for fetching multiple resources simultaneously, which can improve your app’s performance.
7.Versatility
You can use it with both browser-based React and React Native, making it a versatile choice for a wide range of projects.
8.Community Support
Axios has a large and active community, which means you can find extensive documentation, tutorials, and solutions to common problems.
9.Testing
It makes it easier to mock API calls during testing, ensuring the effective testing React components.
10.Customization
You can customize Axios to fit your needs, such as setting default headers, configuring timeouts, or using different HTTP methods.
Prerequisites
You’ll need the following items to follow along with this article:
On your machine, you have Node.js version 10.16.0. Follow the instructions in How to Install Node.js and Create a Local Development Environment on macOS or the Installing Using a PPA part of How To Install Node.js on Ubuntu 18.04 to install this on macOS or Ubuntu 18.04, respectively.
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 isn’t just a library; it’s a developer’s best friend. In addition, it enhances your productivity, keeps your code clean, and ensures your app performs at its best.
Additionally, In this article you have read Several examples of how to utilize Axios inside a React application to generate HTTP requests and manage replies.
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 frontend?
Yes, Axios can be used in the frontend of web applications. It’s a popular JavaScript library for making HTTP requests from a web browser, making it a valuable tool for interacting with APIs and fetching data asynchronously in frontend development.
What is an alternative to Axios in React?
An alternative to Axios in React is the built-in fetch API. fetch is a modern browser feature that allows you to make HTTP requests in a similar way to Axios. It’s commonly used in React applications and provides a lightweight option for handling HTTP requests without external libraries.
Does Axios use fetch internally?
No, Axios does not use the fetch API internally. Axios is a standalone JavaScript library that provides its own implementation for making HTTP requests. While both Axios and fetch serve the same purpose, Axios offers additional features like request and response interceptors and better cross-browser support compared to the fetch API.
How can I import Axios in React?
To import Axios in a React application, follow these steps:
Install Axios using npm or yarn: npm install axios or yarn add axios.
Import Axios in your React component: import axios from ‘axios’;.
You can now use Axios to make HTTP requests in your React component.
Axios react example!
import React, { useEffect, useState } from ‘react’;
import axios from ‘axios’;
function App() {
const [data, setData] = useState([]);
useEffect(() => {
axios.get(‘https://jsonplaceholder.typicode.com/posts’)
.then(response => setData(response.data))
.catch(error => console.error(error));
}, []);
return (
))}