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
Section titled “Start the development server”Start the development server by running the following command in your terminal:
npm run dev
You should see the landing page of our application:
Finding our code
Section titled “Finding our code”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.
-
Copy the text ‘Hello Gamelogger’ from your browser window.
-
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.
-
Press
Enter
to search for the text. -
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.
This is how we can change the page content in Remix.
Let’s now move on to reading data from the database.
Fetch data from the database
Section titled “Fetch 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:
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:
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.