Home > front end >  How to execute a function after setting a state in React Native?
How to execute a function after setting a state in React Native?

Time:02-06

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])

CodePudding user response:

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]);


  •  Tags:  
  • Related