Loading
Current section: Search Engine Optimization 6 exercises
solution

Handling Dynamic Data with Remix's Meta Function

Transcript

00:00 So again, we're going to be in the username route, and we're going to enhance this a little bit so that we can get the user's information. So the meta function accepts a argument that is an object and has a couple of pieces of information that you might find very useful, and one of those is the data.

00:19 And the issue with this, though, is that the data is typed as any because TypeScript isn't aware of the connection between this meta function, the data argument, and the loader. And so we need to inform it of that, and this meta function is a generic that allows

00:37 us to say type of loader. And with that, we're informing TypeScript of our convention that Remix enforces for us. And so we can rely on this convention, and we can use this data, which is stellar. So let's use that to get the user's display name.

00:55 So display name is going to be from data.user.name. Now, this is interesting. Copilot is saying, hey, we can fall back to the username, but we're not actually going to do that. Instead, we're going to use params and do params.username. The reason for that is this meta function

01:14 will run when there is a successful load of the page, but it will also run if there's an error in the loader. So if I throw a new error, oh no, our meta function is still going to run so that when we show our error page, we can have a title and things like that.

01:32 So to address that, we need to consider the fact that data could be undefined. So that's why we have this Elvis operator right here. But if that is the case, then we don't want to use data.user.username because we could still

01:49 potentially end up with no name at all. And because we get the username from the params, or we can get the username from the params, that will be the case whether the loader ran or not. So we can just default to the params.username. If that's not the case for you, for what you're building, maybe you don't have a way to fall back just to the params,

02:08 then you'll just have to do some sort of fall back. It's like unknown or some error or something like that. But falling back on the params, that works just fine for us. OK, so that's the display name. So we can say display name.

02:21 And then check out the, yeah, I think I did like display name. Yeah, check out display name. There we go. That's good enough. You can customize it however you like. So here we have check out Kodi on Epic Notes. We've got Kodi, Epic Notes. We accomplished the task.

02:40 It looks awesome. And we are handling the case where the user does not have a name, as well as the case where the data is not retrievable. So that is how you do dynamic data with the meta in Remix. And I think it's actually pretty sweet that we have such a nice and type safe way to accomplish

03:00 that.