0

But i trying. I need get json from api. I get error:

TypeError: Cannot read property 'setState' of undefined(…)

const Main = React.createClass({
    getInitialState : function() {
    return {
      data: null
    };
 },

 componentDidMount: function() {
     axios.get('https://api')
         .then(function (response) {
            this.setState({data: response.data})
            console.log(response.data);
         })
         .catch(function (error) {
             console.log(error);
         });
        console.log('mount ' + this.state.data );
},
    render() {
        return (
            <h1>{JSON.stringify(this.state.data)}</h1>
        )
    }
})
export default Main;

Why i cant use setState from componentDidMount ?

steelRat
  • 25
  • 4

2 Answers2

0
componentDidMount: function() {  
     var self = this;
     axios.get('https://api')
         .then(function (response) {
            self.setState({data: response.data})
            console.log(response.data);
         })
         .catch(function (error) {
             console.log(error);
         });
        console.log('mount ' + self.state.data );
},

when this is being called its referring to the axios request not the component, so need to set a variable to the this that refers to your component instance that way when you do this.setState its coming from the right this

finalfreq
  • 5,884
  • 1
  • 22
  • 27
0

when you use this you need to know how to use, because the context, you can do two things

 ...
 var setState = this.setState
 axios.get('https://api')
     .then(function (response) {
        setState({data: response.data})
     })
 ...

or you can do

 ...
 axios.get('https://api')
     .then(function (response) {
        this.setState({data: response.data})
     }.bind(this))
 ...
rkmax
  • 15,852
  • 22
  • 82
  • 170