Check out a free preview of the full A Tour of JavaScript & React Patterns course

The "Higher-Order Component Pattern Solution" Lesson is part of the full, A Tour of JavaScript & React Patterns course featured in this preview video. Here's what you'd learn in this lesson:

Lydia codes the solution to the Higher-Order Component Pattern challenge.

Preview
Close

Transcript from the "Higher-Order Component Pattern Solution" Lesson

[00:00:00]
>> So the very first thing that we're going to do is to fetch the data from the URL that was passed as an argument cuz this makes this higher order component super reusable. We're not just fetching from the listing to URL, we can fetch from any URL that we pass to it.

[00:00:14]
So first, we just have to use this effect again. Fetch(url) then res res.json, the normal fetch stuff. And then based on this data, we can set the data. We just have data, setData. It's React.useState. I'm just going to make this only render on initial. And then if there's no data, so this is kind of where the higher-order component logic comes in.

[00:00:45]
We want to show that LoadingSpinner. Now, I'm aware that this could also mean that there has been an error. So normally, you probably also wanna account for that. But in this case, we'll just say if there's no data yet, just return that LoadingSpinner. And otherwise, we will return the element that was passed as this element, so the first one that we wrapped the higher-order component with, and then also pass this data, right?

[00:01:11]
So now when we go back to listings, We don't want to export default the listings, we actually want to import the withLoader higher-order component first, so withLoader from, Let's see how far up I have to go. I think it's twice, hoc/withLoader, yes. And then in here, I'm going to default, so these components.

[00:01:35]
And it also expected that URL from which to fetch it. So I'm just going to pass this one here. And now it will get this as props. So I don't have to use this anymore. And I believe it will be props.listings. So let's see how deeply fetched that is.

[00:01:52]
I'm just gonna check how, See, props data.listings, so okay, props.data.listings, so data, okay, cool. Yeah, so now we created our higher-order component, and you see this little loading spinner spin when there is no data yet. So even if we have multiple components and maybe fetch from another API, we can easily just reuse this withLoader higher-order component by simply passing it another URL.

[00:02:24]
And then probably also another component. Yeah, so that's really cool thing about higher-order components is that they're super reusable, they're super flexible. And it makes it really easy to easily add presentational data and also fetching data.

Learn Straight from the Experts Who Shape the Modern Web

  • In-depth Courses
  • Industry Leading Experts
  • Learning Paths
  • Live Interactive Workshops
Get Unlimited Access Now