React React AJAX call HTTP GET request


Example

Sometimes a component needs to render some data from a remote endpoint (e.g. a REST API). A standard practice is to make such calls in componentDidMount method.

Here is an example, using superagent as AJAX helper:

import React from 'react'
import request from 'superagent'

class App extends React.Component {
  constructor () {
    super()
    this.state = {}
  }
  componentDidMount () {
    request
      .get('/search')
      .query({ query: 'Manny' })
      .query({ range: '1..5' })
      .query({ order: 'desc' })
      .set('API-Key', 'foobar')
      .set('Accept', 'application/json')
      .end((err, resp) => {
        if (!err) {
          this.setState({someData: resp.text})
        }
      })
  },
  render() {
    return (
      <div>{this.state.someData || 'waiting for response...'}</div>
    )
  }
}

React.render(<App />, document.getElementById('root'))

A request can be initiated by invoking the appropriate method on the request object, then calling .end() to send the request. Setting header fields is simple, invoke .set() with a field name and value.

The .query() method accepts objects, which when used with the GET method will form a query-string. The following will produce the path /search?query=Manny&range=1..5&order=desc.

POST requests

request.post('/user')
  .set('Content-Type', 'application/json')
  .send('{"name":"tj","pet":"tobi"}')
  .end(callback)

See Superagent docs for more details.