aliosmankepir
aliosmankepir

Reputation: 171

React Native | useState Async-Await

I have to update the state and use it in the function. It doesn't happen because I can't keep it waiting in the current system. It takes previous data and runs it. How can I hold it?

For example, the last value of the page is 1 when 3. Click is running and it should work as 1 in getReports, but 3 works. The next one is 1, but I need that instant.

const onClick = () => {
    setReports([]);
    setPage(1);
    getReports(); <- use page and reports list
}

Upvotes: 4

Views: 2208

Answers (2)

CodeGeek
CodeGeek

Reputation: 119

Quick solution, get the previous value, increment it and update the state with this new value. In next line, pass same incremented value as argument to getReports(new Value). Here we will be using states only for preserving the last number/index.

But if you want to go with only states then you shouldn't call the getReports() right away, instead you can use useEffect to listen changes to state and then call the method on change. Something like:

const [page, setPage] = React.useState(0);

  React.useEffect(() => {
    getReports();
  }, [page]);

 const onClick = () => {
    setReports([]);

    setPage(1);

    // If page number is always incrementing
    setPage(page+1);
 }

Upvotes: 3

Alex Harwood
Alex Harwood

Reputation: 74

Setting state in React is asynchronous. This is because it re-renders the dom (or parts thereof), and any code after setState (or a hook) is called will continue to execute as normal. Forget async await as far as setting the state is concerned.

In your example, I should just pass the page number to the getReports function. As far as I can tell, there is no need to hold the number is state. Also, the call to setReports([]) looks like it isn't needed either, as getReports should, I assume, overwrite it anyway.

Upvotes: 0

Related Questions