0
class App extends React.Component {
  app: Application;

  ...
  componentDidMound() {
    axios.get(…).then(res => {
        this.app.currentUser = res.data.data; // value assigned here.
        console.log(this.app.currentUser); // and print the current user object.
    };
    console.log(this.app.currentUser); // but here print currentUser = undefined.
  }
}

Why this.app.currentUser assigned in lambda but not outside?

2 Answers2

1

It doesn't hard to understand, axios.get is an async function, so console.log be invoked before axios.get.

Consider:
| |\_____________ console.log | | axios.get | | \ ??? / You can not know which one will be invoked first. Usually isn't axios.get here. If you want to print data, put console.log into callback.

林子篆
  • 84
  • 1
  • 4
0

By using Axios it will create a Promise. The .then is occuring after (when the promise resolves) the console.log which is outside the axios .then.

Also, for what it's worth, setting values like you are is an antipattern.

Here's how I would change your code:

class App extends React.Component {
    state = {
        currentUser: "" // <-- making an assumption that the response is just a string.
    }

    componentDidMount() { // <-- note the actual spelling
        axios.get("http://example.com/").then(res => {
            this.setState({
                currentUser: res.data.data
            });
        });
    }

    render() {
        const { currentUser } = this.state;
        // On initial render currentUser will be an empty string. Once the axios call resolves the setState will be called
        // and it will re-render with the new data.
        return (
            <div>{currentUser}</div>
        );
    }
}
patrick
  • 9,837
  • 3
  • 20
  • 27