john doe john doe - 1 year ago 48
Ajax Question

Can't make a post call in react

I'm learning react and I have started by creating a CRUD app in react. I am able to make the get calls but the post calls don't go through for some reason. My App.js file is:



import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import $ from 'jquery'
import request from "../node_modules/superagent/superagent";
import axios from 'axios'

import {UserForm} from './components/userForm'

class App extends Component {

constructor(props){
super(props)
this.state = {
users: [],
name: '',
email: '',
password: ''
}
this.handleInputChange = this.handleInputChange.bind(this)
this.handlePostRequest = this.handlePostRequest.bind(this);
}

handleInputChange(state, event) {
this.setState({[state]: event.target.value});
}

handlePostRequest(event) {
var data = {
name: this.state.name,
email: this.state.email,
password: this.state.password
}

axios.post('http://localhost:8080/api/users', {
data: data
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});

/*request
.post('http://localhost:8080/api/users')
.set('Content-Type', 'application/x-www-form-urlencoded')
.send({ name: this.state.name, email: this.state.email, password: this.state.password })
.end(function(err, res){
console.log(res.text);
});
var self

event.preventDefault()
self = this

console.log(this.state);

var data = {
name: this.state.name,
email: this.state.email,
password: this.state.password
}

// Submit form via jQuery/AJAX
$.ajax({
type: 'POST',
url: 'http://localhost:8080/api/users',
data: data
})
.done(function(result) {
self.clearForm()
this.setState({result:result})
}).bind(this)
.fail(function(jqXhr) {
console.log('failed to add the user');
}).bind(this)*/
}

componentDidMount() {
this.App();
}

//making a get call
App() {
return $.getJSON('http://localhost:8080/api/users')
.then((data) => {
console.log(data);
this.setState({users:data});
})
}

render() {
return (
<div className="App">
<div className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h2>Welcome to React CRUD App</h2>
</div>
<div className = "Crud-App" >

<div className = "users-list" >
<ul>
{this.state.users.map( user =>
<li key = {user._id} >
{user.name}
</li>
)}
</ul>
</div>

<UserForm handleInputChange = {this.handleInputChange} name = {this.state.name}
email = {this.state.email} password = {this.state.password} />
</div>
</div>
);
}
}

export default App;





And my userForm component file is:



import React from 'react'

export const UserForm = (props) => (
<form>
<label> Name: </label> <input onChange={props.handleInputChange.bind(this, 'name')}
value={props.name} />
<label> Email: </label> <input type="text" onChange={props.handleInputChange.bind(this, 'email')}
value={props.email} />
<label> Password: </label> <input type="text" onChange={props.handleInputChange.bind(this, 'password')}
value={props.password} />
<button type="button" className = "pure-button pure-button-primary" onClick={props.handlePostRequest}>Add User</button>
</form>
)





I have tried ajax, axios, superagent and fetch so far as you can see the commented code in the App.js file. But pressing the submit button does nothing at all. Any help would be appreciated. Thanks

Answer Source

Stateless function components do not have a this. You should not re-bind the onChange handlers in your UserForm component.

Also, rewrite your handler signature so that it only takes the event argument:

  constructor(props) {
    super(props);
    this.makeHandleInputChange = this.makeHandleInputChange.bind(this);
  }

  makeHandleInputChange(state) {
    return e => {
      this.setState({[state]: event.target.value});
    };
  }

Lastly, update your usage of UserForm:

<UserForm
  makeHandleInputChange={this.makeHandleInputChange}
  name={this.state.name} 
  email={this.state.email}
  password={this.state.password} />

and the definition of UserForm itself:

export const UserForm = (props) => (
  <form>
    <label> Name: </label>
    <input
      onChange={props.makeHandleInputChange('name')} 
      value={props.name} />
    { /* ...the rest of the components here... */ }
  </form>
)

EDIT: You are not passing the handlePostRequest as a prop to the UserForm.

<UserForm
  makeHandleInputChange={this.makeHandleInputChange}
  handlePostRequest={this.handlePostRequest}
  name={this.state.name} 
  email={this.state.email}
  password={this.state.password} />
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download