MrDoNotBreak MrDoNotBreak - 3 months ago 29
TypeScript Question

React, Typescript, and Promises

I am trying to write component that calls a webservice and returns some data asynchronously through a promise. once this promise is resolved, i would like to include the results in my component's render method. Ideally i think i would like the results of the promise to be passed into another component. IE; the result of the promise is a list of items.

One more thing - i am writing this React component using Typescript.

Currently i have the following code:

componentWillMount() {
let fooProps = listGetter.returnListData().then((response) => {
return response;
});
}

public render(): JSX.Element {
<div>
<Foo ElementProperties={this.fooProps} />
</div>
}


However, this code errors out and displays "cannot assign null value to property".

What am I doing wrong? What is the best way to handle promise's and resolve them into components in REACT?

Thanks!

Answer

You should use the state of the component.
Changing the state results in a re-rendering of the component, much like how when a component changes the properties of a child results in the child being re-rendered.

Something like:

componentWillMount() {
    listGetter.returnListData().then((response) => {
        this.setState({
            fooProps: response.fooProps
        });
    });
}

public render(): JSX.Element {
    <div>
        <Foo ElementProperties={ this.state.fooProps } />
    </div>
}
Comments