Use axios with React

faminiprodev

Famini-ProDev

Posted on April 22, 2022

Use axios with React

Many projects on the web need to interface with a REST API at some stage in their development. Axios is a lightweight HTTP client based on the $http service within Angular.js v1.x and is similar to the native JavaScript Fetch API.
Axios is promise-based, which gives you the ability to take advantage of JavaScript’s asyncand awaitfor more readable asynchronous code.
You can also intercept and cancel requests, and there’s built-in client-side protection against cross-site request forgery.
In this article, you will see examples of how to use Axios to access the popular JSON Placeholder API within a React application.

Step 1 — Adding Axios to the Project
In this section, you will add Axios to a React project

$ npx create-react-app react-axios-example
Enter fullscreen mode Exit fullscreen mode

To add Axios to the project, open your terminal and change directories into your project:

$ cd react-axios-example
Enter fullscreen mode Exit fullscreen mode

Then run this command to install Axios:

$ npm install axios@0.24.0
Enter fullscreen mode Exit fullscreen mode

Next, you will need to import Axios into the file you want to use it in.

Step 2 — Making a GETRequest

In this example, you create a new component and import Axios into it to send a GETrequest.
Inside your React project, you will need to create a new component named PersonList.
First, create a new componentssubdirectory in the srcdirectory:

$ mkdir src/components
Enter fullscreen mode Exit fullscreen mode

In this directory, create PersonList.js and add the following code to the component:
src/components/PersonList.js:

import React from 'react';
import axios from 'axios';

export default class PersonList extends React.Component {
  state = {
    persons: []
  }

  componentDidMount() {
    axios.get(`https://jsonplaceholder.typicode.com/users`)
      .then(res => {
        const persons = res.data;
        this.setState({ persons });
      })
  }

  render() {
    return (
      <ul>
        {
          this.state.persons
            .map(person =>
              <li key={person.id}>{person.name}</li>
            )
        }
      </ul>
    )
  }
}
Enter fullscreen mode Exit fullscreen mode

First, you import React and Axios so that both can be used in the component. Then you hook into the componentDidMountlifecycle hook and perform a GETrequest.

You use axios.get(url) with a URL from an API endpoint to get a promise which returns a response object. Inside the response object, there is data that is then assigned the value of person.

You can also get other information about the request, such as the status code under res.status or more information inside of res.request.
Add this component to your app.js:

import PersonList from './components/PersonList.js';

function App() {
  return (
    <div ClassName="App">
      <PersonList/>
    </div>
  )
}
Enter fullscreen mode Exit fullscreen mode

Then run your application:

$ npm start
Enter fullscreen mode Exit fullscreen mode

View the application in the browser. You will be presented with a list of 10 names.

Step 3 — Making a POSTRequest

In this step, you will use Axios with another HTTP request method called POST.
Inside your React project, you will need to create a new component named PersonAdd.
Create PersonAdd.js and add the following code to create a form that allows for user input and subsequently POSTsthe content to an API:

src/components/PersonAdd.js:

import axios from 'axios';

export default class PersonAdd 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://jsonplaceholder.typicode.com/users`, { user })
      .then(res => {
        console.log(res);
        console.log(res.data);
      })
  }

  render() {
    return (
      <div>
        <form onSubmit={this.handleSubmit}>
          <label>
            Person Name:
            <input type="text" name="name" onChange={this.handleChange} />
          </label>
          <button type="submit">Add</button>
        </form>
      </div>
    )
  }
}
Enter fullscreen mode Exit fullscreen mode

Inside the handleSubmitfunction, you prevent the default action of the form. Then update the stateto the userinput.
Using POSTgives you the same response object with information that you can use inside of a thencall.
To complete the POSTrequest, you first capture the userinput. Then you add the input along with the POSTrequest, which will give you a response. You can then console.log the response, which should show the user input in the form.
Add this component to your app.js:

src/app.js:

import PersonList from './components/PersonList';
import PersonAdd from './components/PersonAdd';

function App() {
  return (
    <div ClassName="App">
      <PersonAdd/>
      <PersonList/>
    </div>
  )
}
Enter fullscreen mode Exit fullscreen mode

Then run your application:

$ npm start
Enter fullscreen mode Exit fullscreen mode

View the application in the browser. You will be presented with a form for submitting new users. Check the console after submitting a new user.

Step 4 — Making a DELETERequest

In this example, you will see how to delete items from an API using axios.delete and passing a URL as a parameter.
Inside your React project, you will need to create a new component named PersonRemove.
Create PersonRemove.js and add the following code to delete a user:
src/PersonRemove.js :

import React from 'react';
import axios from 'axios';

export default class PersonRemove extends React.Component {
  state = {
    id: ''
  }

  handleChange = event => {
    this.setState({ id: event.target.value });
  }

  handleSubmit = event => {
    event.preventDefault();

    axios.delete(`https://jsonplaceholder.typicode.com/users/${this.state.id}`)
      .then(res => {
        console.log(res);
        console.log(res.data);
      })
  }

  render() {
    return (
      <div>
        <form onSubmit={this.handleSubmit}>
          <label>
            Person ID:
            <input type="number" name="id" onChange={this.handleChange} />
          </label>
          <button type="submit">Delete</button>
        </form>
      </div>
    )
  }
}
Enter fullscreen mode Exit fullscreen mode

Again, the res object provides you with information about the request. You can then console.log that information again after the form is submitted.
Add this component to your app.js:

import PersonList from './components/PersonList';
import PersonAdd from './components/PersonAdd';
import PersonRemove from './components/PersonRemove';

function App() {
  return (
    <div ClassName="App">
      <PersonAdd/>
      <PersonList/>
      <PersonRemove/>
    </div>
  )
}
Enter fullscreen mode Exit fullscreen mode

Then run your application:

$ npm start
Enter fullscreen mode Exit fullscreen mode

View the application in the browser. You will be presented with a form for removing users.

Step 5 — Using a Base Instance in Axios

In this example, you will see how you can set up a base instance in which you can define a URL and any other configuration elements.
Create a separate file named api.js:

$ nano src/api.js
Enter fullscreen mode Exit fullscreen mode

Export a new axiosinstance with these defaults:
src/api.js :

import axios from 'axios';

export default axios.create({
  baseURL: `http://jsonplaceholder.typicode.com/`
});
Enter fullscreen mode Exit fullscreen mode

Once the default instance is set up, it can then be used inside of the PersonRemovecomponent. You import the new instance like this:
src/components/PersonRemove.js :

import React from 'react';

import API from '../api';

export default class PersonRemove extends React.Component {
  // ...

  handleSubmit = event => {
    event.preventDefault();

    API.delete(`users/${this.state.id}`)
      .then(res => {
        console.log(res);
        console.log(res.data);
      })
  }

  // ...
}
Enter fullscreen mode Exit fullscreen mode

Because http://jsonplaceholder.typicode.com/ 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 asyncand await

In this example, you will see how you can use asyncand awaitto work with promises.
The awaitkeyword resolves the promiseand returns the value. The valuecan then be assigned to a variable.

src/components/PersonRemove.js :

import React from 'react';

import API from '../api';

export default class PersonRemove extends React.Component {
  // ...

  handleSubmit = event => {
    event.preventDefault();

    const response = await API.delete(`users/${this.state.id}`);

    console.log(response);
    console.log(response.data);
  }

  // ...
}
Enter fullscreen mode Exit fullscreen mode

*Refrences : *

💖 💪 🙅 🚩
faminiprodev
Famini-ProDev

Posted on April 22, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Angular Form Array
angular Angular Form Array

November 29, 2024

Week 13: Release 0.4: Planning
undefined Week 13: Release 0.4: Planning

November 29, 2024

Can a Solo Developer Build a SaaS App?
undefined Can a Solo Developer Build a SaaS App?

November 29, 2024