0

Consider this scenario:

function myfunc() {
   var total = 0;
   const [ hooka, setHooka ] = useState([]);
   const fetchData = () => {
      api.get().then((data) => {
         total = data.total;
         setHooka(data.value);
      }
   }
   return (
       <h1>{total}</h1>
   );
}

But the total inside the callback scope is different to the one defined in myfunc scope.

How can I set value of total in myfunc scope within the callback?

PS: It is a react hook in actual. Thank you TJ Crowder for the comment. And I've used total = data before a useState trigger method. I can use total as a hook also. But Doesn't creating more hooks slow down rendering in react or what?

PaxPrz
  • 1,778
  • 1
  • 13
  • 29
  • I believe that you are logging the total count, before the total count value assigned from the API. – Riyaz Khan Mar 28 '21 at 12:16
  • Of course its different, you set the value to be the data. What is the problem or question here? – ikiK Mar 28 '21 at 12:16
  • How can I reference to `total` from **myfunc scope** inside the callback? – PaxPrz Mar 28 '21 at 12:17
  • Except the case that the api returns `0`, `total` will of course be changed. The code is doing exactly what you told him to do. – TheEagle Mar 28 '21 at 12:17
  • The problem isn't that the scope is different (your fulfillment handler closes over `total` just fine), the problem is *timing*: `myfunc` has already returned before your fulfillment handler runs. See [this question's answers](https://stackoverflow.com/questions/29516390/how-to-access-the-value-of-a-promise) for how to get the value from a promise, and the other two for general async stuff. – T.J. Crowder Mar 28 '21 at 12:19
  • Nice explaination T.J Crowder. I got it. But it is acutally a React Hook. and There is a render method at the bottom :D – PaxPrz Mar 28 '21 at 12:20

0 Answers0