Search code examples
reactjsreduxes6-promise

How can I delay rendering until then() of promise completes?


I'm using reactjs with redux and this is a part of one of my components.

I want to render postList of the promise which is returned by handleFetchPosts, but the render() function starts rendering before the then() of shouldComponentUpdate is completed.

How can I postpone rendering or rerender after the then is completed?

constructor(props) {
    super(props);
    this.postList = props.postList;
    this.props.handleFetchPosts('/main', 'about', '');
}

shouldComponentUpdate(nextProps) {
    if (this.postList !== nextProps.postList) {
        nextProps.postList.then(data => {
            this.postList = data;
        });
        return true;
    }
    else {
        return false;
    }
}

render() {
    return (
        <div className="content">
            <p>
                {this.postList + ""}
                {/*content*/}
            </p>
        </div>
    );
}

Solution

  • Apologies, I've totally changed my answer, I bypassed the fact you are using Redux.

    The fact that you're using Redux, I'd set up an async action that shouldComponentUpdate calls, which kick-starts the Promise call. This way you can update a flag in your state after starting the Promise to use in the render method to prevent rendering. Once the call has finished send the final ACTION with the results and change the flag back.