kadddeee
kadddeee

Reputation: 498

Decrementing a counter in setState

I am making a slider with three images. For the going backwards button of this slideshow it should start on the last image and go back to 1. The code below when console logged decrements from 3 to 2 BUT MISSES 1, so goes 3 2 3 2 3 2 ... I don't understand why? What is wrong with it.

this.state = {
      imageCount: 0,
   }

previousSlide() {
    this.setState({
      imageCount: 3
    });
    if (this.state.imageCount === 3) {
    this.setState((prevState) => ({
      imageCount: (prevState.imageCount - 1 )
    }));
  }
  console.log("previousSlide", this.state.imageCount)
}

Upvotes: 1

Views: 82

Answers (2)

Jonas Wilms
Jonas Wilms

Reputation: 138257

Because you always set the state to 3, then directly decrement it to 2. You only want to set to 3 if it is 1:

 previousSlide() {
   this.setState(previous => ({
      imageCount: Math.max(previous.imageCount - 1, 0) || 3
   }));
}

Upvotes: 0

intentionally-left-nil
intentionally-left-nil

Reputation: 8274

The simplest solution is just to do the logic inside of setState, that way you only have to call it once:

previousSlide() {
    this.setState({imageCount} => (
      {imageCount: imageCount === 0 ? 3 : imageCount - 1}
    );
  }
}

This code will always set imageCount to 1 less than it was before, unless it's at 0, in which case it will loop to 3.

Upvotes: 1

Related Questions