How to handle REST API requests in React

The REST API is commonly used in Web development.They are programming interfaces that Web applications use to "talk" to each other.They are used to access functional parts and data."REST" (representative state transition) is the concept that defines API properties.This article focuses on how to retrieve data from a database using a Web-based API.

Axios is an npm package that allows applications to send HTTP requests to the Web API.To use Axios in your React application, use the following commands:

npm install axios

Or

yarn add axios

Before creating the react component, follow these steps to import React and Axios into the file:

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

Axios requests are leveraged in the React lifecycle method'componentWillMount'.Although this method has been obsolete since then, it can still be used at the time of writing this article.It will continue until React 17 is released.It is not safe to use it when asynchronous rendering is required.It should be replaced by the "componentDidMount" method.

This method runs after the component is updated to the DOM and is a good place to register API calls.The basic structure so far is as follows:

class YourComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      posts: []
    }
  }
  componentDidMount() {
    // Your axios request here
  }

  render() {
    return (
    //  Your jsx goes here
    );
  }
}

Axios requests have the following basic structure:

axios({ method: 'http request method', url: 'Api url' });

As shown above, the basic request takes an object as a parameter.In this object, a method and a URL key are specified.The HTTP request method type and API URL are set to their respective values.

GET Request

Given this basic pattern, Axios GET requests will look like the following:

const apiUrl = 'Your api address';

axios({ method: 'get', url: `${apiUrl}` });

When the API receives the request and processes it, a response is sent.This component needs to process the received data in some way before it can be used in the application.In this example, we define a key named "posts" in the state and set it to an empty array.Axios requests are asynchronous.We need to process the response by linking "then" to the end of the request.

In the then block, we can update the state of the component as follows:

axios({ method: 'get', url: `${apiUrl}` })
  .then(response => {
    this.setState({
      posts: response.data
    })
  });

(PS).If we use redux for state management, we can call the dispatch function in the'then'block.This allows us to save the response data in redux storage.

POST Request

For a typical POST request, the data is passed along with the API request.This data can usually reside in the state of a component or in a Redux store.Typically, the data users want to publish to the database is derived from the form.We will use the handleChange function to update the state of the component.Our Axios request will be sent in the handleSubmit function.

After submitting the form, the POST request is sent to the API.You can do this by following these steps:

class YourComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      post: ''
    }
  }

  handleChange(e) {
    const { value } = e.target;
    this.setState({
      post: value
    });
  }

  handleSubmit(e) {
    e.preventDefault();

    const { post } = this.state;

    axios({
      method: 'post',
      url: `${apiUrl}/posts`,
      data: post
    })
  }

  render() {
    return (
    //  Your form resides here
    );
  }
}

Delete Request

DELETE requests are similar to POST requests.They are done by interacting with buttons in the view.In this case, when you click the Delete button, you can use the handleClick function to make the request.You can do this by following these steps:

class YourComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      posts: [
        {
          id: 1,
          content: 'The first post'
        }
      ]
    }
    this.handleClick = this.handleClick.bind(this);
  }

  handleClick(e) {
    e.preventDefault();

    const { id } = e.target;
    const apiUrl = 'Your api address';

    axios({
      method: 'delete',
      url: `${apiUrl}/posts/${id}`
    })

  }

  render() {
    const { posts } = this.state;
    return (
      <div>
        {posts.map(post => (
          <div key={post.id}>
            <p>{post.content}</p>
            <div>
              <input 
                type="button"
                id={post.id}
                value="Delete"
                onClick={this.handleClick}
              />
            </div>
          </div>
        ))}
      </div>
    );
  }
}

After clicking the button, send the DELETE request to the api and delete the post from the database.In order to reflect this on the front end, another GET request must be sent to update the state of the component.

JWT Request

JWT (JSON Web token) can be used to authenticate users in Web-based applications.These tokens are usually generated by sending POST requests to the properly configured API.When tokens are generated, they are stored for use through the local store.In this case, the token will need to form part of the HTTP request made.

To illustrate this, we will review the GET request example:

const apiUrl = 'Your api address';
const token = `Bearer ${localStorage.getItem('jwt')}`;

axios({
  method: 'get',
  url: `${apiUrl}`,
  headers: { Authorization: token }
});

The token is passed as another key in the object parameter passed to the Axios call.POST and DELETE requests can be changed in a similar manner, and tokens can be passed through the Header key.

There are.This is a very concise understanding of Axios requests in React front-end components.

Reference material:
https://www.objectx.cn/thread-75-1-1.html

Tags: Web Development axios React Database REST

Posted on Tue, 24 Mar 2020 19:57:55 -0400 by Cynthia Blue