简体   繁体   中英

Axios POST submitting name: field twice

I have a very simple POST form in ReactJS. I have two fields in the form name and description . The form submits, but my issue is that it submits the value of the description into both the name and description fields.

{data: {…}, status: 201, statusText: "Created"
{id: 9, name: "Testing the desc", description: "Testing the desc", …}

my React JS file: import React from 'react'; import axios from 'axios';

export default class NewDistillery extends React.Component {
  state = {
    name: '',
    description: '',
  }

  handleChange = event => {
    this.setState({ name: event.target.value, description: event.target.value });
  }

  handleSubmit = event => {
    event.preventDefault();    
    axios.post(`http://localhost:3000/distilleries.json`, {name: this.state.name, description: this.state.description} )
      .then(res => {
        console.log(res);
        console.log(res.data);
      })
  }

  render() {
    return (
      <div>
          <h2>Add Distillery</h2>
        <form onSubmit={this.handleSubmit}>
          <label className="input-label">
            Name:
            <input className="input" type="text" name="name" onChange={this.handleChange} />
          </label>
          <label className="input-label">
            Description:
            <input className="input" type="text-area" name="description" onChange={this.handleChange} />
          </label>
          <button className="button" type="submit">Add</button>
        </form>
      </div>
    )
  }
}

I tried some options with the setState event such as :

  handleChange = event => {
    this.setState({ name: event.target.value});
    this.setState({ description: event.target.value });
  }

But that's obviously made one difference.

I'm very new to React so not sure where I'm going wrong.

You are overwriting the name and description with the same input value coming from the last input field on submit which is description.

Use the input field name attribute to decide which key to update

Change handleChange to

 handleChange = event => {
    this.setState({ [event.target.name]: event.target.value });
 }

You should follow simple approach:

1- All you inputs should have corresponding state variables with the same name, for example, if you have inputs with names: "name", "description", and "snippet", you should have the same state variables with the exact names, "name", "description", and "snippet".

2- You make a unified handleChange() function, and don't mention input names within it, like:

handleChange = event => {
    this.setState({ [event.target.name]: event.target.value });
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM