Rendering React component using ES generator

I have a very simple implementation of a sleep function that resolves a promise after x miliseconds:

module.exports = (ms) => new Promise(res => setTimeout(res, ms));

      

Then I need to display the component in the component React Stateful Class ES6 after sleep, but it is a sad mistake Objects are not valid as a React child

. Is there something wrong with this generator implementation?

import sleep from './sleep';
class Dummy extends React.Component {

  *renderSubComponent(arg) {
    yield sleep(1000);
    return (<ChildComponent {...arg} />);
  }

  render() {
    return (
     {this.props.check ? this.renderSubComponent(this.props.check).next() : null}
    );
  }

}

      

I cannot use async / await.

+3


source to share


1 answer


Basically, you can't do this implementation because the generator returns an iterator, and if you don't program the iteration, then nothing happens.

A smarter solution for this would be to use component state so that you can store the state in one component and then you can mutate it.



This is how the component will look like

class Dummy extends React.Component {
  constructor(props) {
    super(props);

    this.setState({
      renderSubComponent: false,
    });
  }

  componentDidMount() {
    setTimeout(() => {
      this.setState({
        renderSubComponent: true,
      });
    }, 1000);
  }

  render() {
    const { renderSubComponent } = this.state;
    let subComponent;

    if(renderSubComponent) subComponent = (<ChildComponent check={this.props.check} />);

    return (
      <div>
        {subComponent}
      </div>
    );
  }
}

      

+1


source







All Articles