DEV Community

A Simple(ish) Application of Javascript Generators in React w/ Redux

Helen Liutongco on May 15, 2019

For about a year, I knew what Javascript generators were, but had no experience using them in the wild. I saw an opportunity to try them out when w...
Collapse
 
gsto profile image
Glenn Stovall • Edited

for the issue with state being Async, you can also use a callback function to ensure you are setting it to the correct value.

    function* nextVideo(array){
      let nextVideo = null
      while(this.state.counter < array.length) {
        this.setState((prevState) => {
            nextVideo = array[prevState.counter + 1]
            return { counter: prevState.counter + 1 }
        })
        yield nextVideo
      }
    }
Collapse
 
tonixtuft profile image
Anton Bagdatyev (Tonix-Tuft) • Edited

You are yielding null initially on the very first iteration. Therefore I guess this code won't work because of this test:

  useGenerator = () => {
    this.setState({ generatedObj: this.createVideoGenerator().next() }, () => {
      if(!this.state.generatedObj.value){ // <--- this.state.generatedObj.value will be null instead of the first yielded video React element
        this.props.handleChange("ENDED")
      }
    })
  }