I'm writing a React (well, Preact) app in TypeScript. Page components want to AJAX in their data on load. But I don't know how to do it in a nice way. Maybe there's a convention that I've missed?
Conversation
I could (1) add a wrapper component to get the data and hand it to the "real" component. But that's verbose. Also, if I have a page named Course, I want to name the wrapper Course because it's what's exported. But then what is the inner thing named? It's awkward.
7
I could (2) stick all of the AJAXed data on a single prop of the component, and populate that on load. But that means that the type of that prop is `MyAjaxedData | undefined`, which is awkward because now my code is peppered with conditional access whenever I touch that prop.
4
I'm currently (3) using a "Loader" component that each page subclasses to create its own loader, telling it the path to load from and what component to show once the data is loaded. It works OK, but it's still a bit verbose and it still has the weird duplicate name problem.
1
I can't just do it in component{Will,Did}Mount; see (2) above.
5
One approach I have used is to make a single prop as you described, but without the undefined alternative; make a higher-order wrapper, generic over prop type, which renders a loading UI if prop is undefined, or argument component if prop is present.
1
1
3
This is much like your Loader superclass solution, but I find I can usually abstract away more boilerplate with a higher-order component.
Replying to
I guess it's time for me to do that. I wrote Loader only a few hours into TypeScript, so I was afraid of going full-on HOC. But it should be no problem now!
2

