REACT fetch post request

Kamil Lewandowski picture Kamil Lewandowski · Jul 9, 2017 · Viewed 78.6k times · Source

I have problem with routing post request I need to build register form and post input from form to mongodb I made router and post route on server side and it works ok (when I use postman)

//form is required model​

But I need to fire it form client side, not postman. And here i am lost. I can do it with but when i add onSubmit action it doesnt work. And I need to use new function to fire another thing without redirecting to another page. How to pass this.refs.first_name.value to body so that i could use fetch function?? Below react component

added this JavaScript/JSON snippet

export default class Form extends React.Component {
 constructor(props){
  super(props);
  this.handleSubmit = this.handleSubmit.bind(this);
 }
 handleSubmit(event){ 
  event.preventDefault();
  console.log(this.refs.first_name.value);
  fetch('/', {
   method: 'post',
   body: {
    "first_name": this.refs.first_name.value
   }
  });
 };
 render () {
  return (
   
   <div id="signup">
    <form onSubmit={this.handleSubmit}>
        <input ref="first_name" placeholder="First Name" type="text" name="first_name"/><br />
        <input placeholder="Last Name" type="text" name="last_name"/><br />
       <button type="Submit">Start</button>
    </form>
​
   </div>
​
  )
 }
}

Answer

Amir Hoseinian picture Amir Hoseinian · Jul 9, 2017

I guess the way you are using ref has been deprecated. try below see if you have any luck.

export default class Form extends React.Component {
 constructor(props){
  super(props);
  this.handleSubmit = this.handleSubmit.bind(this);
 }

 handleSubmit(event){ 
  event.preventDefault();
  fetch('/', {
   method: 'post',
   headers: {'Content-Type':'application/json'},
   body: {
    "first_name": this.firstName.value
   }
  });
 };

 render () {
  return (
   
   <div id="signup">
    <form onSubmit={this.handleSubmit}>
        <input ref={(ref) => {this.firstName = ref}} placeholder="First Name" type="text" name="first_name"/><br />
        <input ref={(ref) => {this.lastName = ref}} placeholder="Last Name" type="text" name="last_name"/><br />
       <button type="Submit">Start</button>
    </form>
​
   </div>
​
  )
 }
}

Here is a link to react docs about refs