Using Async/Await with Axios in React

axios-react.png

Prerequisites

  • Basic understanding of JavaScript (Click here)

  • Basic knowledge of React (Click here )

  • Basic understanding of APIs (Click here )

  • Must have Node.js installed locally (Click here )

Getting Started

What is Axios?

Axios is a modern, Promise-based HTTP client library. This means that Axios is used to send an HTTP request and handle their responses, all using JavaScript's promises.

Installing Axios

We need to install Axios: npm install --save axios

Next, let’s try to make a simple get request using Axios from our react component:

   const resp = await axios.get(
      `https://api.github.com/users/${this.state.userName}`
    );

The above code makes a get request to api.github.com/users to retrieve a few users from their API and displays the user’s first name in our component.

Using Async/Await

To use the async/await syntax, we need to wrap the axios.get() function call within an async function.

import React, { Component } from "react";
import axios from "axios";

class Form extends Component {
  state = { userName: "" };

  handleSubmit = async (event) => {
    event.preventDefault();
    const resp = await axios.get(
      `https://api.github.com/users/${this.state.userName}`
    );
      this.props.onSubmit(resp.data);
      this.setState({userName: ''})
  };

  render() {
    return (
      <div>
        <form onSubmit={this.handleSubmit}>
          <input
            type="text"
            value={this.state.userName}
            onChange={(event) =>
              this.setState({ userName: event.target.value })
            }
            placeholder="GitHub Username"
            required
          />

Now, axios.get returns back a promise and to consume this promise, we can await on it and this will give us back a response object. The ''handleSubmit'' function has been labelled async to make the ''await'' call work.

code.PNG

''Axios'' returns response object and then, the data attribute under response object that has the JSON data passed already for us and that is why we have ''resp.data'' this.props.onSubmit(resp.data)

Gotcha!!! You just learnt how to use asyn/await with axios in React.

Note that an async function is different from a sync function in that an async function does not block the page from rendering before the code execution completes.

If you like this article, kindly give me a clap and if there’s anything I’ve missed or you don't fully understand, follow me on twitter @tumipoise, drop your message in the comments' section or send your message to my mail .