How to access data obtained from axioms to display on a web page using js command?

I have ajax functions in api that I am doing axios to get a request from my js response component. How can I access the returned data to display it on a web page.

+6
source share
2 answers

Depends on what you are trying to do, but this is an example.

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

A good way should also be if you use a jet router to call ajax using the onEnter api from the router.

+9
source

Here is one way to do this with React and ES2015. You want to set the default state in the constructor and make a receive request, as in the example below. Just switch the names around to make it work with your application. Then map the array that you will return from the receive request response. Of course, change the names and styles to suit your needs, I use Bootstrap to make it easier 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 
+2
source

All Articles