I am a backend Python developer. But I need to make a simple front on the React. I send a request, I get a response, but I can’t get the state out.

class AppsList extends Component { state = { apps: [] } componentDidMount() { axios.get('/apps') .then(function (response) { console.log(response); this.setState({ apps: response.data }) }) .catch(function (error) { console.log(error); }); } render() { return ( <div> aaa <p>{this.state.apps}</p> aaa </div> ); } } 

Response

enter image description here

2

3 Answers

Try to identify "this" out of the promise and map on this.state.apps like this:

class AppsList extends Component { state = { apps: [] } componentDidMount() { const {setState} = this; axios.get('/apps') .then(function (response) { console.log(response); setState({ apps: response.data }) }) .catch(function (error) { console.log(error); }); } render() { return ( <div> aaa <div> {this.state.apps.map((app) => { return (<p key={app.id}>{app.name}</p>) })} </div> aaa </div> ); } } 
1

The callback is not in arrow notation.

You can simply do:

.then(response => this.setState({ apps: response.data })) 
0

You can do:

class AppsList extends Component { state = { apps: [] } componentDidMount() { axios.get('/apps') .then(function (response) { console.log(response); this.setState({ apps: response.data }) }) .catch(function (error) { console.log(error); }); } render() { return ( <div> aaa <p>{this.state.apps.map(elem => <div>{elem.id} {elem.name}</div>)}</p> aaa </div> ); } } 

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy