-2

Hi it's just very simple problem but why it's not working I don't know. So my code is

  const [i, seti] = useState(0);

I just want to update the state to 1 inc onPress Touchableopacity.It's not working on first tap then in second tap it starts work.

     <TouchableOpacity style={listStyles.buttonstyle2} onPress={() =>
      {     
        console.log('Before  i '+i);
              //trying to update
        seti(current => current + 1);
        console.log('After  i '+i);

        if(i%2==1) {setisPress(false); )  }
        else  {setisPress(true) }
      }
    }>   

1 Answers1

0

use should use useEffect(()=>{...} , [i])

useEffect(()=>{
    console.log('After  i '+i);
    if(i%2==1) {setisPress(false); )  }
    else  {setisPress(true) }
}, [i]) 

return(
  <TouchableOpacity style={listStyles.buttonstyle2} onPress={() =>
      {     
        console.log('Before  i '+i);
              //trying to update
        seti(current => current + 1);
        
      }
    }>  

)

Zahra Mirali
  • 535
  • 3
  • 10