sriram hegde
sriram hegde

Reputation: 2471

counter off by one in react native

I have a counter incrementor in react-native using useState.Whenever I press a button the count should increase by one. it works fine however when first press happens the counter is still 0 when the second press happens the counter increases by one and continues smoothly with no problem. Why isn't it updating on the first press? here is code:

import { StatusBar } from 'expo-status-bar';
import React, {useState } from 'react';
import { StyleSheet, Text, View, Button } from 'react-native';

export default function App() {
  
  const [count, setCount] = useState(0);
  const [outputState, setOutputState] = useState(`You have tapped ${count} times`);

  const getFinalResult = () => {
    setCount(count => count + 1);
    setOutputState(`You have tapped ${count} times`);
    
  }
  return (
    <View style={styles.container}>
      <Text>{outputState}</Text>
      <Button title="change text" onPress={getFinalResult} />
      <StatusBar style="auto" />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});

Upvotes: 0

Views: 136

Answers (1)

Ferin Patel
Ferin Patel

Reputation: 3998

This code will work for you. You was setting the state and displaying at the same time. Setting State is async task and it required some time to complete.

import { StatusBar } from 'expo-status-bar';
import React, {useState } from 'react';
import { StyleSheet, Text, View, Button } from 'react-native';

export default function App() {
  
  const [count, setCount] = useState(0);

  return (
    <View style={styles.container}>
      <Text>You have tapped {count} times</Text>
      <Button title="change text" onPress={() => setCount(count => count + 1)} />
      <StatusBar style="auto" />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});

Upvotes: 1

Related Questions