score:12

Accepted answer

Depends of what you trying to do but this is a example.

componentDidMount() {
  axios
    .get(`endpoint`)
    .then(res => this.setState({ posts: res.data }))
    .catch(err => console.log(err))
}

A good way too should be if you using react-router to make the ajax call with the onEnter api from the router.

score:5

Here is one way of doing it with React and ES2015. You will want to set the default state in the constructor and make your get request like in the example below. Just switch the names around to make it work with your application.Then map over the array you get back from the response of the get request. Of course change the names and stylings to suit your needs, I'm using Bootstrap to make things easy to understand. Hope this helps.

  import React, { Component } from 'react'
  import axios from 'axios';
  import cookie from 'react-cookie';
  import { Modal,Button  } from 'react-bootstrap'
  import { API_URL, CLIENT_ROOT_URL, errorHandler } from '../../actions/index';

  class NameofClass extends Component {

      constructor(props) {
        super(props)

        this.state = {
          classrooms: [],
          profile: {country: '', firstName: '', lastName: '', gravatar: '', organization: ''}
        }
      }
      componentDidMount(){
        const authorization = "Some Name" + cookie.load('token').replace("JWT","")
          axios.get(`${API_URL}/your/endpoint`, {
            headers: { 'Authorization': authorization }
          })
          .then(response => {
            this.setState({
              classrooms:response.data.classrooms,
              profile:response.data.profile
            })
          })
          .then(response => {
            this.setState({classrooms: response.data.profile})
          })
          .catch((error) => {
            console.log("error",error)
          })
      }
      render () {
        return (
          <div className='container'>
            <div className='jumbotron'>
              <h1>NameofClass Page</h1>
              <p>Welcome {this.state.profile.firstName}  {this.state.profile.lastName}</p>
            </div>
            <div className='well'>
               {
                 this.state.classrooms.map((room) => {
                    return (
                      <div>
                        <p>{room.name}</p>
                      </div>
                    )
                 })
               }
            </div>
          </div>
        )
      }
    }

    export default NameofClass

Related Query

More Query from same tag