Chris Allen
Chris Allen

Reputation: 15

how to get data out of .then function

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>
    );
  }
}

Upvotes: 0

Views: 3043

Answers (2)

meyi
meyi

Reputation: 8112

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.

Upvotes: 1

shivam dhankani
shivam dhankani

Reputation: 99

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
              });
            }
          )
      }

Upvotes: 1

Related Questions