Quantcast
Channel: Active questions tagged react-native+typescript - Stack Overflow
Viewing all articles
Browse latest Browse all 6287

React Native: Counter not showing correct updated state

$
0
0

Im trying to put together a simple counter which changes the quantity of an item. Using Hooks to manage its state, i update the value on screen correctly. However, the value the state holds when i console log is always one less than the value on the screen.

For example:

If starting value is 1, after pressing the plus button, the value on screen changes to 2 but in console the state value is still 1.

Setup of Hooks and functions controlling the count:

//Set Item priceconst [itemPrice, setItemPrice] = useState(itemOptions[0].price)//Counter Control const [disableMinus, setDisableMinus] = useState(true);const addQuantity = () => {    if (quantity === 1) {        setQuantity(quantity + 1);        setDisableMinus(false);    } else {        if (quantity > 1){            setItemPrice(itemOptions[0].price * quantity);            setQuantity(quantity + 1);            setDisableMinus(false);        }    }}const minusQuantity = () => {   if (quantity === 1){       setDisableMinus(true);   } else {       if (quantity > 1) {           setQuantity(quantity - 1);           setDisableMinus(false);       }   }} return (<View style={{flexDirection: 'row', alignItems: 'center', justifyContent: "center", paddingVertical: 20}}><TouchableOpacity disabled={disableMinus} onPress={() => minusQuantity()}><AntDesign style={{color: '#37BD6B'}} name="minuscircle" size={30}/></TouchableOpacity><Text style={{paddingHorizontal: 10, fontWeight: '700', fontSize: 30}}>{quantity}</Text><TouchableOpacity onPress={() => addQuantity()}><AntDesign style={{color: '#37BD6B'}} name="pluscircle" size={30}/></TouchableOpacity>
)

Thanks in advance


Viewing all articles
Browse latest Browse all 6287

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>