score:2

Accepted answer

the way you are using should throw the error, check the console. you need to bind the context to use this keyword inside callback method that you are using in .then, use this:

componentdidmount() {
    axios.get('http://localhost:4000/api/v1/events')
        .then( response => {
            console.log('data', response.data);
            this.setstate({events: response.data});
        })
        .catch(function (error) {
            console.warn(error);
        });
}

or use .bind(this) to bind the context, like this:

componentdidmount() {
    axios.get('http://localhost:4000/api/v1/events')
        .then(function (response) {
            this.setstate({events: response.data});
        }.bind(this))
        .catch(function (error) {
            console.warn(error);
        });
}

score:0

this

inside callback doesn't refer to your component context for that you need to bind your callback function of axios with your react component to update state of that component

import react, {proptypes, component} from 'react';
import axios from 'axios';
import './app.css';


class app extends component {

constructor(props) {
    super(props);
    this.state = {
        events: []
    };
}

componentdidmount() {
    axios.get('http://localhost:4000/api/v1/events')
        .then(function (response) {
            this.setstate({events: response.data});
        }.bind(this)) // binding of callback to component
        .catch(function (error) {
            console.warn(error);
        });
}

render() {    
    // this.state.events keeps being an empty array []
    return (
        <div classname="home">
          {
            this.state.events.map((month) => {
              console.log(month) 
            })
          }
        </div>
    );
}

}

score:1

you need to bind axios success function to the correct context to make use of setstate. use this

componentdidmount() {
        axios.get('http://localhost:4000/api/v1/events')
            .then(function (response) {
                this.setstate({events: response.data});
            },bind(this))
            .catch(function (error) {
                console.warn(error);
            });
    }

Related Query

More Query from same tag