You don’t have to worry about over-fetching when using Prisma. Just use the
.findMany method from Prisma and pass it an object with a
select property. In the
select you can choose exactly what properties that you want off of objects fetched from the database.
We’ll continue following the .server file pattern we established in an earlier lesson and create an async function in
post.server.ts that fetches posts with only their slugs and titles. We can then use this function in our components.
Kent C. Dodds: [0:00] One thing you might have noticed when we were loading these posts is that were getting some data on here that we don't need for this display at all. That is what we call data over-fetching, which is one of the reasons why people like to reach for GraphQL because it solves this problem.
[0:15] In Remix, you don't have a data over-fetching problem. You're just simply sending more data than you need to. What we're going to do is in my post.server, I'm going to export a new function, a async function, called getPostListings.
[0:31] This is going to also findMany, but we're going to select only the parts of the data that we actually need in our UI. What do we need? We need the slug and we need the title. That's really all. That's all that we need.
[0:48] We're going to come over here. Instead of getPosts, we're going to say, getPostListings. Now, we're still getting the slug and the title, all of that type checks just fine. If we come over here and we go to the home page, clear all this out, go to the "Blog Posts," and look at the data, now, we're only getting the slug and the title.
[1:09] We have just optimized the data that we're sending to the client to reduce the amount of data that is being sent. All it took was going to our post.server and making a more specific query for the data that we need.
[1:22] Now, we could also have taken our getPosts as we had before and simply plucked off the pieces of the posts that we didn't need. That would have worked just as well because again, the loader only runs on the server.