2

What is the best way to solve this UI usecase using react hooks - tiles screenshot

I have tiles that each need to make request to backed API REST endpoints. The number of tiles is configurable for every module, so ideally I want to have some configuration with array of items like

{title, text, asyncRequestFunction}

and based on that configuration array I want to do multiple async and concurrent requests to load data. Each tile should show some spinner when the appropriate request is in progress and show data as soon as they arrive, not after all the data are available. Can I solve it by some currently available hooks like react-hooks-async?

What really gets in my way is that react hooks cannot be called in loop.

skyboyer
  • 22,209
  • 7
  • 57
  • 64
  • does the third case here help you? https://stackoverflow.com/questions/54002792/should-i-use-one-or-many-useeffect-in-component – Andus Jan 10 '20 at 16:34

1 Answers1

0

Not completely sure I am answering your question Jirko, because it's usually better to show some code example of stuff you already tried.

From top of my head, I would have container component where configuration is pulled. Then mapped array of tiles from configuration and rendered child components with whatever settings you need passed as props.

Like this each child component can take care of it's own fetching inside useEffect or any hook you use from the library.

Additionally hooks are not supposed to work inside of the loop, that's anti-pattern.

iamwtk
  • 1,031
  • 3
  • 13
  • 24
  • Thank you for your reply. I would like to keep the TilesComponent pure without hooks. It will only render itself based on props given from the upper component, let's call it a container. I think it is more generic than. The component does not need to know, where the data comes from and how. It only knows it has some text, title, color etc... But this way I ran into trouble because doing several async requests in the container is not possible with existing async hooks. The only possibility I found is writing custom async-hook that will accept configuration and do several requests at once. – Jiří Balatý Jan 11 '20 at 22:07