Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to execute a function after setting a state in React Native?

my problem is I need to execute a function (getCupons) after setting the two states setPagenumber and setMoreresults but this two functions are asynchronous and don’t have a callback. Thanks

const [pageNumber, setPagenumber] = useState(1);
const [moreResults, setMoreresults] = useState(true);
const isFocused = useIsFocused();


useEffect(() => {
    setPagenumber(1);
    setMoreresults(true);
    getCupons();
}, [isFocused])

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You can create another useEffect, then it will be called when the conditions are met.

  const [pageNumber, setPagenumber] = useState(0);
  const [moreResults, setMoreresults] = useState(false);
  const isFocused = useIsFocused();

  useEffect(() => {
    setPagenumber(1);
    setMoreresults(true);
  }, [isFocused]);

  useEffect(() => {
    if (moreResults && pageNumber === 1) {
      getCupons();
    }
  }, [pageNumber, moreResults]);


Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading