4

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
}
aliosmankepir
  • 139
  • 10
  • Please elaborate and add as much information to the question as possible so an adequate answer can be given – Colin Oct 16 '20 at 09:21

2 Answers2

3

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);
 }
CodeGeek
  • 119
  • 5
0

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.

Alex Harwood
  • 64
  • 1
  • 2
  • I wouldn't use the page anyway, but since I use the reports list on flatlist, shouldn't it be in state? – aliosmankepir Oct 16 '20 at 09:32
  • Yes, store the list of reports in state by calling setReports(data) where data is the response from an api call, or from wherever you are getting your data. I assume the getReports() function needs to know which page you are on? If so, then pass it as a parameter rather that getting it from state. If I have misunderstood, you may need to clarify your question. – Alex Harwood Oct 16 '20 at 09:39