How to use Axios with React.js

How to use Axios with React.js

Table of Content

  • Introduction

  • Prerequisites

  • Step 1: Adding Axios to our Reactjs Project

  • Step 2: How to make a GET Request

  • Step 3: How to Make a POST Request

  • Step 4: How to Make a DELETE Request

  • Step 5: How to Create an Axios Instance

  • Conclusion

Introduction

Because Axios is promise-based, you may utilize JavaScript's async and await for more understandable asynchronous code.

There is built-in client-side security against cross-site request forgery, as well as the ability to intercept and cancel requests.

You will see examples of using Axios to access the well-known JSON Placeholder API within a React application in this post.

Prerequisties

The following are necessary for you to follow along with this article:

  • Your machine has Node.js 10.16.0 set up. Follow the instructions in How to Install Node.js and Create a Local Development Environment on macOS or How to Install Node.js on Ubuntu 18.04's Installing Using a PPA section to install this on macOS or Ubuntu 18.04.
  • The How to Set Up a React Project with Create React App guide may be used to create a new React project with Create React App.
  • Additionally, having a fundamental understanding of HTML and CSS as well as JavaScript, which you can get in the How To Code in JavaScript series, will be helpful.

Step 1: Adding Axios to our Reactjs Project

We are going to be following step-by-step on how to make use of Axios in our react project, To add Axios o our project. Firstly, Create a React App using the code below

npx create-react-app projectname

Then, we have to add Axios to the project

cd projectname

we are inside our dir now !!, Then run the command to install Axios

npm install axios@0.24.0

Now, We are going to import Axios to the file we want to use in.

Step 2: How to Make a GET Request

Make a GET request to obtain or fetch data. You are going to ask for individual posts first. You are receiving the initial post from the /posts endpoint if you look at the endpoint.

Inside our project, we create a new component and name it i.e Getlist

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

mkdir src/components

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

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

export default class GetList 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>
    )
  }
}

To make sure that both may be utilized in the component, you must first import React and Axios. Then you issue a GET request after hooking into the componentDidMount lifecycle hook. Additionally, you can find more details inside of res.request or the request's status code under res.request.

To your app.js, inside the component.

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

function App() {
  return (
    <div ClassName="App">
      <GetList />
    </div>
  )
}

Then run your application:

npm run start

Then, check the result in your browser.

Step 3: How to Make a POST Request

In this stage, you'll employ Axios with the POST HTTP request method.

You must add a brand-new component with the name ValuePost to your React project.

The following code should be added to ValuePost.js to construct a form that accepts user input and then POSTs the content to an API:

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

export default class ValuePost 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>
    )
  }
}

When you use POST, you receive the same response object with data that you can utilize in a then call.

You must first gather the user's input before you can finish the POST request. You then combine the input with the POST request, which results in a response. After that, you can console.log the answer should display the data that the user entered into the form.

Add this component to your app.js:

import GetList from './components/GetList';
import ValuePost from './components/ValuePost';

function App() {
  return (
    <div ClassName="App">
      <GetList />
      <ValuePost />
    </div>
  )
}

Then run your application:

npm run start

Then, check the result in your browser.

Step 4: How to Make a DELETE Request

The DELETE method should then be used to remove a resource.

It's important to note that you can fulfill this request without using any additional arguments:

You must add a new component called PersonRemove to your React project.

To remove a user, create PersonRemove.js and add the following code:

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>
    )
  }
}

Once more, the res object gives you details about the request. After the form has been submitted, you can console.log that information once more.

Include this part in your app.js:

import GetList from './components/GetList';
import ValuePost from './components/ValuePost';
import PersonRemove from './components/PersonRemove';

function App() {
  return (
    <div ClassName="App">
      <GetList />
      <ValuePost />
      <PersonRemove />
    </div>
  )
}

Then run your application:

npm run start

Then, check the result in your browser.

Step 5: How to Create an Axios Instance

You can see from the preceding examples that the endpoint used by Axios to execute these queries includes a baseURL.

To continually write that baseURL for each request, though, becomes tiresome. Since the baseURL you use always uses the same endpoint, couldn't you just have Axios remember it?

Actually, you can. Axios will remember that baseURL and any additional data you might want to include in each request, such as headers, if you create an instance using the.new() method.

import axios from "axios";
import React from "react";

const client = axios.create({
  baseURL: "https://jsonplaceholder.typicode.com/posts" 
});

export default function App() {
  const [post, setPost] = React.useState(null);

  React.useEffect(() => {
    client.get("/1").then((response) => {
      setPost(response.data);
    });
  }, []);

  function deletePost() {
    client
      .delete("/1")
      .then(() => {
        alert("Post deleted!");
        setPost(null)
      });
  }

  if (!post) return "No post!"

  return (
    <div>
      <h1>{post.title}</h1>
      <p>{post.body}</p>
      <button onClick={deletePost}>Delete Post</button>
    </div>
  );
}

The endpoint is passed to the baseURL field of the configuration object above.

In this case, client is the name of the newly created instance that the.create() function returns.

The baseURL is no longer required to be given as the first argument when using any of the previous methods in the future. You simply need to reference the desired route.

Conclusion

In this article, you looked at many examples of how to create HTTP requests and manage responses in a React application using Axios.

I'm hoping this manual was very helpful to you.

Did you find this article valuable?

Support Abidoye Oluwatobi's Blog by becoming a sponsor. Any amount is appreciated!