React Axios Post Request

  Aug 2023
  ITSolutionsGuides
  Category: React JS
React Axios Post Request

Hi Developers,

We are going to see how to send POST request using Axios library

Let's Start Coding


  • Lets declare two states input & errors

  • In handleChange event it stores the value in input state

  • On form submit it calls handleSubmit which futher calls validate()

  • The validate function verify the input and stores errors if input is not validate

  • If isValid = true is true it sends request else it displays error

import React from 'react';
import axios from 'axios';
  
class CreatePost extends React.Component {
    constructor() {
    super();
    this.state = {
      input: {},
      errors: {}
    };
     
    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }
     
  handleChange(event) {
    let input = this.state.input;
    input[event.target.name] = event.target.value;
  
    this.setState({
      input
    });
  }
     
  handleSubmit(event) {
    event.preventDefault();
  
    if(this.validate()){
  
        const post = this.state.input;
  
        axios.post(`https://jsonplaceholder.typicode.com/posts`, { post })
        .then(res => {
          console.log('res');
          console.log(res);
          console.log(res.data);
  
          let input = {};
          input["title"] = "";
          input["body"] = "";
          this.setState({input:input});
  
          alert('Post created successfully.');
  
        })
   
    }
  }
  
  validate(){
      let input = this.state.input;
      let errors = {};
      let isValid = true;
  
      if (!input["title"]) {
        isValid = false;
        errors["title"] = "Please enter your title.";
      }
  
      if (!input["body"]) {
        isValid = false;
        errors["body"] = "Please enter your body.";
      }
  
      this.setState({
        errors: errors
      });
  
      return isValid;
  }
     
  render() {
    return (
      <div>
        <h1>React Axios Post Request Example - ITSolutionsGuides</h1>
        <form onSubmit={this.handleSubmit}>
  
          <div className="form-group">
            <label for="title">Title:</label>
            <input 
              type="text" 
              name="title" 
              value={this.state.input.title}
              onChange={this.handleChange}
              className="form-control" 
              placeholder="Enter title" 
              id="title" />
  
              <div className="text-danger">{this.state.errors.title}</div>
          </div>
  
          <div className="form-group">
            <label for="body">Body:</label>
            <textarea 
              name="body"
              value={this.state.input.body} 
              onChange={this.handleChange}
              placeholder="Enter body"
              className="form-control" />
  
              <div className="text-danger">{this.state.errors.body}</div>
          </div>
              
          <input type="submit" value="Submit" className="btn btn-success" />
        </form>
      </div>
    );
  }
}
  
export default CreatePost;

We hope it helps everyone. Thanks for supporting ITSolutionsGuides and keep supporting us also follow us in social media platforms.

Subscribe for NewsLetter

Be the first to know about releases and tutorial news and solutions.

We care about your data in our privacy policy.

ITSolutionsGuides

ITSolutionsGuides was started mainly to provide good and quality web solutions for all the developers. We provide tutorials to support all the developers and also we try to provide solutions to the errors we face while coding.

Contact US

ITSolutionsGuides, provide users with an easy-to-use form to reach out for support or inquiries.

whatsapp  gmail  instagram-new--v1  facebook-circled  twitter-circled  linkedin  github  pinterest 

Copyright © 2023 - 2024 All rights reserved | ITSolutionsGuides