0

Note: I believe someone already asked this question but when I tried looking for it, it suddenly disappeared. If anyone knows where the answer is, can they point me in that direction please? Thanks!

I'm creating a functional component in React using the instructions on https://reactjs.org/docs/faq-ajax.html - where it says "equivalent with Hooks". The only difference is that I'm getting a single item object, not an array.

However, if I try to log the value of isLoaded and item, it seems to appear 3 times in the console:

  1. false, {}
  2. true, {}
  3. true, {object populated now}

So if I try to do the return like the sample says, it will end up inside of the "else" condition after the second iteration of this console logging and if I try to call any properties of that empty object, the page errors out. I have to add another condition to make sure the object is populated before being able to return the JSX, but I'm pretty sure this is the wrong thing to do.

Is there a way to make sure the JSX is only getting returned once rather than these three times, and only returning it when the fetch completes?

I have tried turning this into a Class component but had the same problem. I'd rather not rely on State as there's nothing really dynamic about this page.

jenn hi
  • 51
  • 3
  • can you post some of your code? – tcf01 Feb 03 '21 at 02:25
  • 1
    This has to do with how `setState` actions are batched, if you swap the order of your `setIsLoaded` and `setItems` from the example this should work as intended. In general any `setState` in `useEffect` or a synthetic event should be batched together and a single rerender occurs, except when the `setState` is called asynchronous (i.e. your promise) see https://stackoverflow.com/a/60822508/4364635 for a more indepth answer. – Jacob Smit Feb 03 '21 at 03:14
  • Yes, that makes a lot of sense, and it worked. Thank you! – jenn hi Feb 03 '21 at 20:11

0 Answers0