How to Render State in Reactjs?

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

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

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

James H. Sterling

James H. Sterling

Environmental Science & Climate Journalist

James Sterling reports on renewable energy developments, climate policy, ecological conservation, and green tech innovations around the globe.

Share this article
Twitter Facebook Pinterest