Benjamin Li Benjamin Li - 1 month ago 16
React JSX Question

In react with redux, how to do post request

for async examples, I have seen fetch data from server. But what about post request? how to do that? I don't want to use

jquery.ajax
to do that, because I don't even want to import
jquery


thanks

Answer

The most simple approach would be to use fetch, which is built-in in most browsers. You can also look into other, more versatile options like SuperAgent, which needs to be required but is much smaller than jQuery. Here's a basic example combining React and fetch:

class Example extends React.Component {
  constructor() {
    super();
    this.state = { user: {} };
    this.onSubmit = this.handleSubmit.bind(this);
  }
  handleSubmit(e) {
    e.preventDefault();
    var self = this;
    fetch('http://reqres.in/api/users', { 
        method: 'POST',
        data: {
          name: self.refs.name,
          job: self.refs.job
        }
      })
      .then(function(response) {
        return response.json()
      }).then(function(body) {
        console.log(body);
      });
  }
  render() {
    return (
      <form onSubmit={this.onSubmit}>
        <input type="text" placeholder="Name" ref="name"/>
        <input type="text" placeholder="Job" ref="job"/>
        <input type="submit" />
      </form>
    );
  }
}

ReactDOM.render(<Example/>, document.getElementById('View'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.0/react-dom.min.js"></script>
<div id="View"></div>

Keep in mind that you might need to include a polyfill for fetch depending on which browsers you want to support.

Example on JSBin, since it might not work here.