Home > Enterprise >  React Native - useState set data update late
React Native - useState set data update late

Time:11-19

So in my app, my button is supposed to set my data, then navigate into the next page. The problem here is that the data is not updated fast enough (I think). The console show null (which is the initial data I set), then it navigate to the next page carrying the null data. If I go back to the previous page then go to the next page again, it will carry the previous data that is not sent before. I tried setTimeout but I guess it's a wrong way to use setTimeout.

  const [foto, setFoto] = useState(null);

  const sendQUtest = () => {
    setFoto('QUtest');
    setTimeout(() => {
      console.log('assessmentTimeout: '   foto);
    }, 5000);
    console.log('assessment: '   foto);
    navigator.navigate('pembayaranAssessment', foto);
  };
  const sendTOPtest = () => {
    setFoto('TOPtest');
    console.log('assessment: '   foto);
    navigator.navigate('pembayaranAssessment', foto);
  };

I wonder if there is anyway to wait for the data. The solution I saw in others question is using useEffect, but in this one I need it after the onPress.

CodePudding user response:

usestate is Asynchronous and you cannot really make an await function for it there is two approaches one of them is using useEffect hook like the following,you can have multiple useEffect in one function use useEffect to check when value changes and then navigate

    const [foto, setFoto] = useState(null);
       useEffect(()=>{
//this will fire  at the beginning and on foto changing value
if(foto == null){
//will ignore first run
}else{ navigator.navigate('pembayaranAssessment', foto); 
}},[foto])

  const sendQUtest = () => {
    setFoto('QUtest');
    setTimeout(() => {
      console.log('assessmentTimeout: '   foto);
    }, 5000);
    console.log('assessment: '   foto);
    //navigator.navigate('pembayaranAssessment', foto);
  };
  const sendTOPtest = () => {
    setFoto('TOPtest');
    console.log('assessment: '   foto);
   // navigator.navigate('pembayaranAssessment', foto);
  };

CodePudding user response:

YES setstate will take some time to update, you can directly send data to your navigate function

navigator.navigate('pembayaranAssessment', 'TOPtest');

CodePudding user response:

Try this way

 const sendQUtest = () => {
    setFoto('QUtest');
    setTimeout(() => {
      navigator.navigate('pembayaranAssessment', foto); // add here
    }, 200);
  };

  const sendTOPtest = () => {
    setFoto('TOPtest');
    setTimeout(() => {
      navigator.navigate('pembayaranAssessment', foto); // add here
    }, 200);
  };
  • Related