6

new in react here, don't know if it's right to do this on the setState callback like this?

           setTimeout(()=> {
            this.setState((state, props) => ({ activateLightColorForRed: true }), () => {
              setTimeout(()=> {
                this.setState(()=> ({ activateLightColorForRed: false }))
              }, 500);
              red.play();
            })
          }, toWait); 

or maybe something like this?

 this.setState((state, props) => {
    this.setState((state, props) => {
      activateLightColorForRed: true
    });
    setTimeout(() => { activateLightColorForRed: false },500)
  })

are the state on the setState callback updated? something weird is happening in my components, it's rendering multiple times. I am not sure but I think it's because I'm doing the first sample?

2
  • 1
    could you post the full code for the component? Are you calling setState from within the render method? Commented Sep 11, 2017 at 22:26
  • 1
    Heads-up @i-am-newbie : setState are asynchronous in nature and you could also use simply this.setState({activateLightColorForRed:true}) i.e. pass a object instead of passing in a function. Might help in readability. And yeah post the complete code for the component. It will help us. Thanks Commented Sep 12, 2017 at 3:23

1 Answer 1

12

Your question does not seem to follow the pattern of a regular react app. You should be using the lifecycle events to react to the state being changed. You should not be making multiple, nested, confusing callbacks (like it seems you want to do).

Might I suggest a structure more like this

class Foo extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      activateLightColorForRed: false,
    };
  }
  componentDidUpdate(prevProps, prevState) {
    if (this.state.activateLightColorForRed) {
      // when the state is updated (turned red), 
      // a timeout is triggered to switch it back off
      this.turnOffRedTimeout = setTimeout(() => { 
        this.setState(() => ({activateLightColorForRed: false}))
      }, 500);
    }
  }
  componentWillUnmount() {
    // we set the timeout to this.turnOffRedTimeout so that we can
    // clean it up when the component is unmounted.
    // otherwise you could get your app trying to modify the state on an
    // unmounted component, which will throw an error
    clearTimeout(this.turnOffRedTimeout);
  }
  render () {
    // really simply ui to show how it *could* work
    return (
      <div onClick={this.turnLightRed}>
        The light is {this.state.activateLightColorForRed ? "Red" : "Green"}.
        <br /> Click to change!
      </div>
    )
  }
  turnLightRed = () => {
    // this function will turn the light red
    this.setState(() => ({ 
      activateLightColorForRed: true 
    }));
  }
}

ReactDOM.render(
  <Foo name="World" />,
  document.getElementById('container')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.0/react-dom.min.js"></script>
<div id="container"></div>

Hope that helps.

Sign up to request clarification or add additional context in comments.

6 Comments

being new in react this is very helpful. most of the time i have to re read docs.
From React docs: "This method is not called for the initial render." This won't work.
What are you talking about @YasinYaqoobi? Please be more specific to what you think won't work
componentDidUpdate is not called on initial render reactjs.org/docs/…, so the timeout never gets called. Even after clicking when the state is red, it doesn't automatically change to "green"
componentDidUpdate is not supposed to fire onLoad. It fires after the state is updated; when the button is clicked. Then the timeout starts and reverts the state after 500ms. I am quite confident that this works.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.