Grey Haven
Grey Haven

Reputation: 380

How to resolve async call within componentWillMount() before render()

Trying to figure out how to call async functions in componentWillMount() before the render() method is called. I have the following code (stripped down for simplicity's sake):

interface State {
    foo?: AClass
}
export class BClass extends React.Component<Props, State>
{
    async componentWillMount(){
        await this.run();
    }
    async run(){
        let a = await bar();
        this.setState({foo: a});
    }
    render() {
        return (
            <View>
                <Text> {this.state.foo == null ? "null" : this.state.foo.getText()} </Text>
            </View>
        );
    }
}

I've seen one potential fix involving adding a loading variable to this.state, but that doesn't really do much. I've also tried messing around with returning Promise and then doing fooPromise.then((c)=>{this.setState({foo: a})}); but to no avail.

All this to ask, is there a way I can call a blackbox async method within componentWillMount() and resolve the result before running render()?

Upvotes: 0

Views: 1503

Answers (1)

Matt Aft
Matt Aft

Reputation: 8936

You can just make it render nothing until its done:

export class BClass extends React.Component<Props, State>
{
    state = {
      loaded: false,
    }
    async componentWillMount(){
        await this.run();
    }
    async run(){
        let a = await bar();
        this.setState({ foo: a, loaded: true });
    }
    render() {
        return (
            <View>
                {this.state.loaded &&
                  <Text> {this.state.foo == null ? "null" : this.state.foo.getText()} </Text>
                }
            </View>
        );
    }
}

Upvotes: 2

Related Questions