Search code examples
reactjssetstate

How to set state , keep getting TypeError: Cannot read property 'setState' of undefined


Im trying to set the state with the data coming back from the axios get.But I keep getting this error TypeError: Cannot read property 'setState' of undefined.

class Page extends React.Component {

constructor(props) {
    super(props);
    this.authenticated = props.authenticated;
    //this.handleClick = this.handleClick.bind(this);
} 

state ={
    page : []
}

componentDidMount() {
    let config = null;
    //let token = null;
    app.auth().currentUser.getIdToken(true).then(function(idToken) {
        config = {
            headers: {'Authorization': idToken}
        };
        console.log(config);
        axios.get('http://localhost:4001/api/v1/page',config)
        .then(res => {
            console.log(res.data);
          const page = res.data;
          this.setState( page );
        }).catch((err)=>{
            console.log(err);
        });

     })

  }

render () {

    const authenticated = this.authenticated;
    console.log(authenticated);
    console.log(this.state);

    return (
        <h1> test 123</h1>
      );
}

}


Solution

  • this inside axios refers to a different thing, store the value of this in a variable and use that variable

    componentDidMount = () => {
      let config = null;
      //let token = null;
      const current = this; // here save this in current variable
      app
        .auth()
        .currentUser.getIdToken(true)
        .then(function(idToken) {
          config = {
            headers: { Authorization: idToken }
          };
          console.log(config);
          axios
            .get('http://localhost:4001/api/v1/page', config)
            .then(res => {
              console.log(res.data);
              const page = res.data;
              current.setState(page); // use current here
            })
            .catch(err => {
              console.log(err);
            });
        });
    }