Skip to content

Reading data - loader functions

We are now ready to read data from the database using Prisma and Remix.

Let’s get started!

Start the development server by running the following command in your terminal:

Terminal window
npm run dev

You should see the landing page of our application:

Hello Gamelogger

How can we work out where this page is coming from?

The easiest way is to simply copy the ‘Hello Gamelogger’ text and search for it in the codebase. Let’s do that now.

  1. Copy the text ‘Hello Gamelogger’ from your browser window.

  2. In VS Code, press CTRL + Shift + F to open the project search bar, or click the magnifying glass icon at the top left of your screen.

    Paste the text you copied into the search bar.

  3. Press Enter to search for the text.

  4. Should see an exerpt of code from the app/routes/index.tsx file.

    Click on the file name to open the code in your editor.

    Project Search

This is how we can change the page content in Remix.

Let’s now move on to reading data from the database.

We now need to fetch the games from the database and display them on the page.

We will do this by adding a Remix loader function to the _index.tsx file:

app/routes/_index.tsx
import { PrismaClient } from '@prisma/client'
import { json } from '@remix-run/node'
import { useLoaderData } from '@remix-run/react'
import type { MetaFunction } from "@remix-run/node";
6 collapsed lines
export const meta: MetaFunction = () => {
return [
{ title: "New Remix App" },
{ name: "description", content: "Welcome to Remix!" },
];
};
export async function loader() {
const prisma = new PrismaClient()
const games = await prisma.game.findMany()
return json({ games })
}
export default function Index() {
const { games } = useLoaderData<typeof loader>()
console.log({ games })
return (
<div className="flex items-center justify-center min-h-screen">
<h1 className="text-4xl font-bold">Hello, world!</h1>
</div>
);
}

Save these changes, then head over to your browser and refresh the page.

Right-click on the page, choose ‘Inspect’ and check the ‘Console’ tab.

You should see the game we have loaded from the database displayed in the console:

Console log of games

This is great!

It means that we have successfully loaded data from the server, and passed this across to the client. And all in a single file! 😎

In our case, we want to use the games data to render a list of games on the page.

We will do this in the next section.