0

I make an API call to ContractService.getAppData(). The object it returns, appDataResult will always contain a success key which will be a boolean.

The issue is that the request succeeds, but before it prints console.log('success'), it prints console.log('failure'). Meaning the request is interpreted as failed at first, which effects the related logic which is important to the app state.

const fetchAppData = async () => {
  try {
    const appDataResult = await ContractService.getAppData()
    if (appDataResult.success) {
      console.log('success')
     // Related logic
    } else {
      console.log('failure')
     // Related logic
    }
  } catch (e) {
    console.error(e)
  }
}

The fetchAppData function is called from a useEffect like so:

 useEffect(() => {
  if(isLoggedIn && isSelectedAsset) {
    fetchAppData()
  }
 }, [isLoggedIn, isSelectedAsset])

What am I missing?

flow24
  • 793
  • 2
  • 5
  • 17
  • 1
    The function is being called twice. The only way for an if/else to run both the if and the else is if the if/else is being ran twice with a different values. – Kevin B Apr 26 '21 at 19:38
  • How are you calling `fetchAppData`? The code you are showing here seems fine. So the error is probably happening when calling this function. – derpirscher Apr 26 '21 at 19:41
  • Bu the failure is logged first. When in fact it shouldn't print at all, it always succeeds or fails. Shouldn't two runs log the same value? – flow24 Apr 26 '21 at 19:43
  • Does this answer your question? [UseEffect being called multiple times](https://stackoverflow.com/questions/62631053/useeffect-being-called-multiple-times) – derpirscher Apr 26 '21 at 19:44
  • If you are making two requests to the server (as suggested by your result), it's not completely unexpected that the failure would happen first. If the first request sent locks a resource that the second needs, the second may fail immediately and finish before the first, thus logging failure before success – Kevin B Apr 26 '21 at 19:44
  • You can easily determine whether your code is being called twice by setting a breakpoint at `if (appDataResult.success) {` and see how many times it is called. You also need to trace where `isLoggedIn` and `isSelectedAsset` are getting changed because apparently at some point they are both true, then one is false, then both are true again. – Heretic Monkey Apr 26 '21 at 19:50
  • Thank you all. It does make a first call too early, when a specific element of the request is not ready yet which prints the failure, then makes another call with that element ready and I get success. – flow24 Apr 26 '21 at 19:58

1 Answers1

3

The only way it can print failure, then success, is if your function is being called twice. You need to check where fetchAppData() is being called.

Also, to get another obvious failure out of the way - is there another console.log('failure') anywhere?

divillysausages
  • 7,883
  • 3
  • 25
  • 39