There has a been a huge push for functional programming and subsequently the use of Functional Components over Class Components. I’m not going to try and sell you on Functional Components as there are existing blog posts that do that.
Since Functional Components are just pure functions, they come with some limitations, namely it being mostly static and not dynamic. Functional Components are pretty dumb due to the lack of state. As a result, they can’t make asynchronous requests on their own. Hence, I wrote asyncify, a React Higher-Order Component that allows you to do just that.
Why I wrote asyncify
The reason I wrote asyncify was not to use Functional Components every chance that I got to, but rather because I found making GET requests within Class Components repetitive and similar, and thus common patterns and boilerplate can be abstracted away.
Why you should use asyncify
Simply put, less boilerplate. Compare the code to fetch the 5-day forecast from OpenWeather done with a Class-Based Component and the same thing doing with asyncify and a Functional Component:
Class Component Approach:
Functional Component Approach with asyncify:
Thefunction returns an object that has to be passed into the function. Inconvenient, I know! I have been breaking my brain figuring out how to abstract that out. The function is necessary to handle more than one async requests within the same functional component.
More about asyncify
Two or more async requests
Even if you had more than one async request, the component is only going to rerender once. This was the solution to an issue where more requests were sent than was needed when making more than one async request.
The async requests take place in the async-parallel library.function, where they are sent in parallel thanks to the
Accessing the fetched data
The object returned from the async function passed into thefunction has the data property containing the fetched data. Before it is fetched, however, the data property contains the value defined in , the second argument of the asyncify HOC.
Before the async request is complete, you might want to have a placeholder value. You need to pass in an object with all the placeholder values into the second argument of the asyncify HOC:
The key value ofmust correspond with the first argument of the function.
To have a loader instead of a placeholder value, have the placeholder value be undefined and make use of conditional rendering to show the loader.
Most likely figuring out how to abstract away thefunction, and handling errors when an async request fails.
You can check out asyncify on GitHub with documentation and examples. Let me know what your thoughts are on this. Is it useful, is it redundant, is it just plain stupid?