How to submit form data in post request using axios

In this instructional, you’re going to find out how you’ll be able to ship submitted kind records in a put-up request in React the use of axios.

Believe we now have an <LoginForm /> element with two enter fields and a post button.

similarly, you might also like What are React Stripes in React?

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

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

  const handleSubmit = (match) => {
    // we can fill this within the coming paragraph
  }

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

  go back (
    <kind onSubmit={handleSubmit}>
      <p>Login Shape</p>
      <enter
        kind="e-mail"
        identify="e-mail"
        placeholder="input an e-mail"
        cost={formValue.e-mail}
        onChange={handleChange}
      />
      <enter
        kind="password"
        identify="password"
        placeholder="input a password"
        cost={formValue.password}
        onChange={handleChange}
      />
      <button
        kind="post"
      >
        Login
      </button>
    </kind>
  )
};

export default LoginForm;

To create a form-data we can use FormData Internet API, which retail outlets fields and its values as key-value pairs.

Subsequent, make a HTTP POST request in axios with loginFormData handed as a records belongings cost within the axios request object.

const handleSubmit = async() => {
  // retailer the states within the kind records
  const loginFormData = new FormData();
  loginFormData.append("username", formValue.e-mail)
  loginFormData.append("password", formValue.password)

  take a look at {
    // make axios put up request
    const reaction = anticipate axios({
      approach: "put up",
      url: "/api/login",
      records: loginFormData,
      headers: { "Content material-Sort": "multipart/form-data" },
    });
  } catch(error) {
    console.log(error)
  }
}

Leave a Comment

Your email address will not be published. Required fields are marked *

Let's Get in Touch

Read our customer feedback

Please fill in the form below.


    To top