DEV Community

MokaDevLight
MokaDevLight

Posted on

Use Axios with React

This tutorial was verified with Node.js v16.13.1, npm v8.1.4, react v17.0.2, and axios v0.24.0.

Step 1 — Adding Axios to the Project
In this section, you will add Axios to a React project you created following the How to Set up a React Project with Create React App tutorial.

“npx create-react-app react-axios-example”

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

“cd react-axios-example”

Then run this command to install Axios:

“npm install axios@0.24.0

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

Step 2 — Making a GET Request

In this example, you create a new component and import Axios into it to send a GET request.

Inside your React project, you will need to create a new component named PersonList.

First, create a new components subdirectory in the src directory:

“mkdir src/components”

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

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 componentDidMount lifecycle hook and perform a GET request.

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”

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

Step 3 — Making a POST Request

import React from 'react';
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 handleSubmit function, you prevent the default action of the form. Then update the state to the user input.

Using POST gives you the same response object with information that you can use inside of a then call.

To complete the POST request, you first capture the user input. Then you add the input along with the POST request, which will give you a response. You can then console.log the response, which should show the user input in the form.

Step 4 — Making a DELETE Request

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

Thanks for posting.

Top comments (0)