Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does useState not increment

I'm trying to implement useState to store an incrementing value. When I try incrementing the value it doesn't update it. I have tried manually setting the value to a specific number and this does work. What is wrong?

const [cardsIndex, setCardsIndex] = useState(0);

       <Card style={[styles.card, styles.card1]} key={index}
          onSwipedRight={(event) => { setCardsIndex(cardsIndex+1);}}
          onSwipedLeft={(event) => { setCardsIndex(cardsIndex+1);}}
       >
like image 562
chackerian Avatar asked Jan 31 '26 05:01

chackerian


2 Answers

Whenever you want to update the state based on previous value of the state then you must use a function in setState.

i.e.

setCardsIndex((prevValue) => prevValue + 1)

Docs: https://reactjs.org/docs/hooks-reference.html#functional-updates

like image 136
Mubashir Hassan Avatar answered Feb 01 '26 19:02

Mubashir Hassan


Just change :

onSwipedRight={(event) => { setCardsIndex(cardsIndex+1);}}
onSwipedLeft={(event) => { setCardsIndex(cardsIndex+1);}}

to :

onSwipedRight={(event) => {() => { setCardsIndex(cardsIndex =>cardsIndex+1);}}
onSwipedLeft={(event) => { () => { setCardsIndex(cardsIndex =>cardsIndex+1);}}}
like image 43
monim Avatar answered Feb 01 '26 18:02

monim



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!