Reputation: 85
I have ajax functions in an api to which I'm making an axios get request from my react js component. How can I access the returned data to display it on the web page.
Upvotes: 6
Views: 26524
Reputation: 1618
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
Upvotes: 5
Reputation: 5929
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.
Upvotes: 12