Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Axios Post Form with Reactjs

So I have this post method with Axios and if I submit this, it said

Uncaught (in promise) Error: Network Error at createError (createError.js:16) at XMLHttpRequest.handleError (xhr.js:87)

If I use this method:

axios.post('http://localhost:5000/users', ({userid: this.state.userid})

it works. But if I add 2 or more arg to the axios post it gets error again:

axios.post('http://localhost:5000/users', ({userid: this.state.userid}, {fullname: this.state.fullname} ))

Here is my full code. As you can see I try different combinations of code, and it only works if I only pass 1 arg.

import React from 'react';
import axios from 'axios';
// import { Form } from 'antd';
// import { List, Card, Form } from 'antd';

export default class FormUser extends React.Component {
    // constructor(props) {
    //   super(props)
    //   this.state = {
      state = {
        userid: '',
        fullname: '',
        usergroup:'',
        emailid: '',
        mobile: '',
        title: '',

  };

  handleChange = event => {
    this.setState({ userid: event.target.value });
    this.setState({ fullname: event.target.value });
    this.setState({ usergroup: event.target.value });
    this.setState({ emailid: event.target.value });
    this.setState({ mobile: event.target.value });
    this.setState({ title: event.target.value });
  }

  handleSubmit = event => {
    event.preventDefault();

    // const userform = {userid: this.state.userid};
    // const fullnameForm = {fullname: this.state.fullname};
    // const usergroupForm = {usergroup: this.state.usergroup};
    // const emailidForm = {emailid: this.state.emailid};
    // const mobileForm = {mobile: this.state.mobile};
    // const titleForm = {title: this.state.title};

    axios.post('http://localhost:5000/users', ({userid: this.state.userid}, {fullname: this.state.fullname} )) 
    // { {userid: this.state.userid}, {fullname: this.state.fullname} , usergroup: this.state.usergroup, emailid: this.state.emailid, mobile: this.state.mobile, title: this.state.title }) 
    // { userform, fullnameForm, usergroupForm, emailidForm, mobileForm, titleForm }) 
      .then(res => {
        console.log(res);
        console.log(res.data);
      })
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <label>User Project ID:  <input type="text" name="userid" onChange={this.handleChange}/></label><br/>
        <label>Full Name:  <input type="text" name="fullname" onChange={this.handleChange}/></label><br/>
        <label>User Group:  <input type="text" name="usergroup" onChange={this.handleChange}/></label><br/>
        <label>Email:  <input type="text" name="emailid" onChange={this.handleChange}/></label><br/>
        <label>Mobile:  <input type="text" name="mobile" onChange={this.handleChange}/></label><br/>
        <label>Title:  <input type="text" name="title" onChange={this.handleChange}/></label>
        <button type="submit">Add</button>
      </form>
    )
  }
}

AXIOS POST on Express

app.post('/users', function (req, res) {
  var postData = req.body;
  // postData.created_at = new Date();
  connection.query("INSERT INTO users SET ?", postData, function (error, results, fields) {
    if (error) throw error;
    console.log(results.insertId);
    res.end(JSON.stringify(results));
  });
});
like image 418
Eko Andri Avatar asked May 31 '18 06:05

Eko Andri


2 Answers

eventHandler for each state. Is there any way I can do this better? yes it would work something like this

import React, { Component } from 'react';

class UserForm extends Component {
  constructor() {
    super();
    this.state = {
      fname: '',
      lname: '',
      email: '',
    };
  }

  onChange = (e) => {
    /*
      Because we named the inputs to match their
      corresponding values in state, it's
      super easy to update the state
    */
    this.setState({ [e.target.name]: e.target.value });
  }

  render() {
    const { fname, lname, email } = this.state;
    return (
      <form>
        <input
          type="text"
          name="fname"
          value={fname}
          onChange={this.onChange}
        />
        <input
          type="text"
          name="lname"
          value={lname}
          onChange={this.onChange}
        />
        <input
          type="text"
          name="email"
          value={email}
          onChange={this.onChange}
        />
      </form>
    );
  }
}

and about submission of the form your axios post would work something like this

onSubmit = (e) => {
    e.preventDefault();
    // get our form data out of state
    const { fname, lname, email } = this.state;

    axios.post('/', { fname, lname, email })
      .then((result) => {
        //access the results here....
      });
  }
like image 69
Afaq Ahmed Khan Avatar answered Oct 19 '22 05:10

Afaq Ahmed Khan


axios.post(url[, data[, config]])'s 3rd argument is the Axios configuration object, which you're inadvertently passing in in

axios.post('http://localhost:5000/users', ({userid: this.state.userid}, {fullname: this.state.fullname} ))

so the request gets misconfigured and doesn't work.

Instead, all of the data to POST should be in the single data object.

axios.post('http://localhost:5000/users', {
  userid: this.state.userid,
  fullname: this.state.fullname,
})
like image 39
AKX Avatar answered Oct 19 '22 03:10

AKX