How To Use Axios with React
Introduction
At some point during their development, many web applications will need to interact with a REST API. 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.
Axios is promise-based, allowing you to use JavaScript’s async and await functions for more understandable asynchronous programming.
You may also intercept and cancel requests, and cross-site request forgery is protected on the client side.
In this post, we’ll look at how to utilize Axios to access the popular JSON Placeholder API from within a React project.
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, which can be found in the How To Code in JavaScript course, as well as a basic understanding of HTML and CSS, would also assist.
A fundamental grasp of JavaScript, which can be found in the How To Code in JavaScript course, as well as 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.
This component should be added to your app.
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
In Conclusion, Several examples of how to utilize Axios inside a React application to generate HTTP requests and manage replies were covered in this article.
Leave a Reply
Want to join the discussion?Feel free to contribute!