Current section: Server Components 27 exercises
solution

Server Context

Loading solution

Transcript

00:00 First, let's create our async local storage module. So we'll come here, we'll say async storage.js. And we're going to import. I bet our AI Assistant can do this. Come on. OK, fine. It's going to be async local storage from async hooks. And we'll say node colon to get that. And then we're going to export our async local storage,

00:18 but we're going to call this ship data storage. So then throughout our application, we can reference ship data storage. In here, we're going to have our ship data storage wrap all of this async stuff in a context.

00:35 So let's stick that in there. And this actually does take a first property. We've got props here, but we're going to rename this to data because it makes more sense to be data. And then instead of passing that as props,

00:51 we're just going to access it via the ship data storage. So if I dive into our app, we no longer need these props. I'm going to cut that out. And we're going to get it from const. That comes from ship data storage dot get store.

01:10 And that takes care of that. So sweet. Then we can grab this right here, get rid of that. And we'll dive into the search results. We'll grab this, cut that out. And const that equals ship. We don't need to await. We can if we wanted to, like we could,

01:28 because we're using a server component. And that's kind of cool, but we don't need to. And our ship data storage is going to come from ship data storage. Sweet. And then if we come back here and then dive into our ship fallback, we'll

01:46 get rid of the props on the ship fallback. Cut that out. Say const that is ship data storage dot get store. Sweet. And that takes care of that one. And then finally, get rid of the props on the ship details. Remove that. Cut that out.

02:06 Say const that equals ship data storage get store. Oh, snap. And we are in an excellent place. Save all that. Format it nicely. Oh, man, that looks so nice. OK, refresh. And everything is still working as it was before. You can still go to different pages.

02:22 You can still perform a search, all working as we want it to. So looks awesome. I think it's great. And using async local storage, a platform API from Node, we're able to expose whatever data

02:39 we want to to all the async things that are going on inside of the context of this callback. And then all of those things can access the data from the ship data storage, which is pretty cool. We've eliminated prop drilling.

02:56 We make things that are truly global, accessible anywhere. I probably wouldn't do this everywhere just to avoid prop drilling problems. But for global things, like stuff that comes off the request and stuff like that, definitely makes sense. So I'm a fan.