Search code examples
react-nativebuttonstateonpress

If I use onPress on any of my buttons they all change state. I want independent states


If I use onPress on any of my buttons they all change state, they show the same value. I want them to be independent of each other using the same 2 functions (increment and decrement).

this.state = {
   packs: 0
};

incrementPacks = () => {
    this.setState({
      packs: this.state.packs + 1
    })
  }

  decrementPacks = () => {
    this.setState({
      packs: this.state.packs - 1
    })
  }

<View style={styles.iceBtnContainer}>
    <Button title='-' onPress={this.decrementPacks} />
    <Text style={styles.count}>{this.state.packs}</Text>
    <Button title='+' onPress={this.incrementPacks} />
</View>


<View style={styles.bufPadBtnContainer}>
    <Button title='-' onPress={this.decrementPacks} />
    <Text style={styles.count}>{this.state.packs}</Text>
    <Button title='+' onPress={this.incrementPacks} />
</View>

Solution

  • You could do something like this

    this.state = {
       icePacks: 0,
       bufPadPacks: 0
    };
    
    incrementPacks = type => {
       if(type === "Ice") {
        this.setState({ icePacks: this.state.icePacks + 1 })
       } else if(type === "BufPad") {
        this.setState({ bufPadPacks: this.state.bufPadPacks + 1 })
      }
    
      }
    
      decrementPacks = type => {
       if(type === "Ice") {
        this.setState({ icePacks: this.state.icePacks - 1 })
       } else if(type === "BufPad") {
        this.setState({ bufPadPacks: this.state.bufPadPacks - 1 })
      }
    
      }
    
    <View style={styles.iceBtnContainer}>
        <Button title='-' onPress={() => this.decrementPacks("Ice")} />
        <Text style={styles.count}>{this.state.icePacks}</Text>
        <Button title='+' onPress={() => this.incrementPacks("Ice")} />
    </View>
    
    
    <View style={styles.bufPadBtnContainer}>
        <Button title='-' onPress={() => this.decrementPacks("BufPad")} />
        <Text style={styles.count}>{this.state.bufPadPacks}</Text>
        <Button title='+' onPress={() => this.incrementPacks("BufPad")} />
    </View>