0

trying to read outside of a then/catch statment. It works fine inside .then but doesn't work inside of react html

class DashboardPage extends Component {
...

  componentDidMount() {
    axios.get('http://localhost:3000/users/me', this.yourConfig)
  .then(function (response) {
    // handle success
    console.log(response.data.name)
    console.log(response.data.email)

  })
 ....


  render() {
    return (
      <div className="App">
     <p>Welcome {this.response.data.name}</p>
     <p>Your email is {this.response.data.email}</p>
      this is your token {this.tokenCookie}

      </div>
    );
  }
}
Emile Bergeron
  • 17,074
  • 5
  • 83
  • 129
Chris Allen
  • 15
  • 1
  • 5

2 Answers2

1

You need to save response to the state. Something like this should work:

class DashboardPage extends Component {
    constructor(props) {
        super(props);
        this.state = {response: null};
    }

...

  componentDidMount() {
    axios.get('http://localhost:3000/users/me', this.yourConfig)
    .then((response) => {
      // handle success
      console.log(response.data.name)
      console.log(response.data.email)
      this.setState({ response });
    });
  }
.... 
  render() {
    if (this.state.response == null) {
      return (<div className="App"><p>Response not loaded</p></div>); // Whatever you want to render when there is no response yet
    } else {
      return (
      <div className="App">
        <p>Welcome {this.state.response.data.name}</p>
        <p>Your email is {this.state.response.data.email}</p>
        this is your token {this.tokenCookie}
      </div>
      );
    }
  }

Note: I changed the function (function (response)) to the ES6 arrow function so this can be used. You can also set a variable like var that = this and change this inside function (response) to that.

meyi
  • 7,574
  • 1
  • 15
  • 28
  • Be careful, setting the state in an async callback may happen after the component was unmounted. https://reactjs.org/blog/2015/12/16/ismounted-antipattern.html – Emile Bergeron Jul 10 '19 at 18:34
  • I tried your way and now i am getting TypeError: Cannot read property 'data' of null – Chris Allen Jul 10 '19 at 18:43
  • My bad @ChrisAllen, I forgot to update render to test for that. If `response` is null, you have to render something else. I updated the code to reflect it. – meyi Jul 10 '19 at 18:55
1

You cannot use response variable outside that function The best way around is use state Example in doc -> https://reactjs.org/docs/faq-ajax.html

 componentDidMount() {
        fetch("https://api.example.com/items")
          .then(res => res.json())
          .then(
            (result) => {
              this.setState({
                isLoaded: true,
                items: result.items
              });
            },
            // Note: it's important to handle errors here
            // instead of a catch() block so that we don't swallow
            // exceptions from actual bugs in components.
            (error) => {
              this.setState({
                isLoaded: true,
                error
              });
            }
          )
      }
  • Be careful, setting the state in an async callback may happen after the component was unmounted. https://reactjs.org/blog/2015/12/16/ismounted-antipattern.html – Emile Bergeron Jul 10 '19 at 18:34