Loaders are used to get data into your components from the server. We can set up a loader by defining an async function named loader
outside of our route component. That function will return a new Response
, with some JSON in the case of this lesson.
Then to use the data in our component, we’ll use the nice useLoaderData
hook that Remix gives us, which gets the data returned from your loader.
What’s extra cool is that in Remix your loaders will only run on the server. They won’t even be included in the browser bundle!
Kent C. Dodds: [0:00] Let's create a bunch of posts, and we'll create a listing of those posts. Right here, we'll bring in { Link } from "@remix-run/react". If we refresh over here, we're going to see our post right there.
[0:12] Of course, we don't want to have all of our posts in the component. We wouldn't want that bundled, and so we're going to export const loader, and that's an async function that returns a response. We'll say newResponse and here's our posts. Then, we'll have our headers to say that the content type is application/json.
[0:34] Our posts, maybe this will be a postString because our body needs to be a string. Let's move these posts up here. Let's make our postString = JSON.stringify(post). Then down here, we're going to get our posts from a destructured useLoaderData. Here, I think we're going to want to have this be an object that has a post property so those two match. Cool.
[1:03] Then, we'll have this post. We go over here and just double check to reload. That is still working as it was before, but now, this is coming from the server. This loader will never ever get sent to the browser. We can test that. If we go to the home page first, let's clear all this stuff out, and if we go to the blog posts, we'll see we are making a network request to get all of that data.
[1:27] This is all that we're sending across the wire. We're not sending the code for all of this stuff, just the JSON response. I'm not a huge fan of the newResponse thing here. I don't want to do Content-Type: application/json for every single time. We're pretty much always going to do that in my loader. We're going to bring in a handy-dandy utility called { json } from "@remix-run/node".
[1:51] Then, I can use json instead of this newResponse. We can say json. Instead of the postString, we can just do POST. Instead of the headers and all of that stuff, we can just get rid of that. We can, of course, still include headers if we need to, but we don't have to include the Content-Type, which saves us a little bit of trouble.
[2:09] Now, we refresh over here, and everything is still working swimmingly. In review, we wanted to get some data into this component. We created a loader. We're using the json helper to create a response. We're using useLoaderData to get that