Yamileth Flores
Yamileth Flores

Reputation: 3

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

Upvotes: 0

Views: 81

Answers (1)

Tarik
Tarik

Reputation: 597

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


Upvotes: 3

Related Questions