How to submit form data in post request using axios

#react #axios

Last updated on Aug 1, 2021 by Suraj Sharma



In this tutorial, you will learn how you can send submitted form data in a post request in React using axios.


Consider we have a <LoginForm /> component with two input fields and a submit button.


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

const LoginForm = () => {
  
  const [formValue, setformValue] = React.useState({
    email: '',
    password: ''
  });

  const handleSubmit = (event) => {
    // we will fill this in the coming paragraph
  }

  const handleChange = (event) => {
    setformValue({
      ...formValue,
      [event.target.name]: event.target.value
    });
  }

  return (
    <form onSubmit={handleSubmit}>
      <p>Login Form</p>
      <input
        type="email"
        name="email"
        placeholder="enter an email"
        value={formValue.email}
        onChange={handleChange}
      />
      <input
        type="password"
        name="password"
        placeholder="enter a password"
        value={formValue.password}
        onChange={handleChange}
      />
      <button
        type="submit"
      >
        Login
      </button>
    </form>
  )
};

export default LoginForm;


To create a form-data we will use FormData Web API, which stores fields and its values as key-value pairs.

Next, make a HTTP POST request in axios with loginFormData passed as a data property value in the axios request object.


const handleSubmit = async() => {
  // store the states in the form data
  const loginFormData = new FormData();
  loginFormData.append("username", formValue.email)
  loginFormData.append("password", formValue.password)

  try {
    // make axios post request
    const response = await axios({
      method: "post",
      url: "/api/login",
      data: loginFormData,
      headers: { "Content-Type": "multipart/form-data" },
    });
  } catch(error) {
    console.log(error)
  }
}


Related Solutions


Rate this post


Suraj Sharma is a Full Stack Software Engineer. He holds a B.Tech degree in Computer Science & Engineering from NIT Rourkela.