Reset State Counter in React Native

I am new to react native. Currently, I am building a state counter (increment) and I need to limit the state value. Whenever the state value reach more than 1, it is reset back to 0. I already tried using 'if' function in code. But, 'This.setState' is prohibited to use inside return function. Maybe someone can help? Thanks a lot.

export default class index extends Component {
  constructor(props){
    super(props)

    this.state = {
      Lamp: 0,
      Aerator: 0,
    }
  }

  InitialState(){
    if(this.state.Aerator > 1)
    return {
     this.state.Aerator: 0
    }    
  }

  IncrementA(){
    this.setState({Aerator: this.state.Aerator + 1});
    console.log(this.state.Aerator);
  }

  IncrementB(){
    this.setState({Lamp: this.state.Lamp + 1});
    console.log(this.state.Lamp);
  }

  renderElement(){
    if(this.state.Aerator == 1)
       return {
        tintColor: 'grey'
       }
  }


  render () {
    return (
      <View style={styles.container}>

      <View style={{flexDirection: 'row', top: -240, position: 'relative', width: 240, height: 60, alignContent: 'center', justifyContent: 'space-between', alignItems: 'center'}}>
        <TouchableOpacity onPress={() => {
          this.IncrementA();
        }}>
          <Image
          source={require('../../assets/drawable-hdpi/aerated-clipart-png-fan-icon-png-transparent-png-full-size-aeration-png-940_980.png')}
          style={{resizeMode: 'contain', width: 60}}
          />
        </TouchableOpacity>

        <TouchableOpacity onPress={() => {
          this.IncrementB();
        }}>
          <Image
          source={require('../../assets/drawable-hdpi/unnamed.png')}
          style={{resizeMode: 'contain', width: 60, height: 60, alignItems: 'center'}}
          />
        </TouchableOpacity>
      </View>

    </View>
    )
  }
}

Upvotes: 0

Views: 721

Answers (1)

Kartikey
Kartikey

Reputation: 5002

Try something like this -

Snack link to see working example

import * as React from 'react';
import { Text, View, StyleSheet, Button } from 'react-native';
import Constants from 'expo-constants';

export default function App() {
  const [Counter, SetCounter] = React.useState(0);

  const ChangeValue = () => {
    if (Counter >= 5) {
      console.log('Can Increase till 5 Limit only')
      SetCounter(0); // This will reset the counter
    } else {
      SetCounter(Counter + 1);
    }
  };

  return (
    <View style={styles.container}>
      <Text style={{ marginBottom: 10 }}>Current Count = {Counter}</Text>
      <Button title="Increase" onPress={() => ChangeValue()} />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    paddingTop: Constants.statusBarHeight,
    backgroundColor: '#ecf0f1',
    alignItems: 'center',
    padding: 8,
  },
});

Upvotes: 1

Related Questions