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
23 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> ); } } 1The callback is not in arrow notation.
You can simply do:
.then(response => this.setState({ apps: response.data })) 0You 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> ); } }
