Filter articles by category
Objectives
Section titled βObjectivesβOur news index page is looking great, but itβs missing one key feature: the ability to filter articles by category.
If you try clicking between the different news categories, youβll notice that the URL and page title changes, but the articles donβt update:
In this guide, weβll update the loader
function in our app/routes/news.$category.tsx
file to filter articles by category and if they are published or not.
Revisiting the loader
function
Section titled βRevisiting the loader functionβAt the moment, our loader
function is fetching all articles from the database:
export async function loader({ params }: LoaderFunctionArgs) { const { category } = params
invariant(typeof category === 'string', 'Category not found') const categoryTitle = toTitleCase(category)
const allArticles = await prisma.article.findMany({ select: { id: true, title: true, category: { select: { name: true } }, images: { select: { id: true } }, }, })
return json({ categoryTitle, allArticles })}
Letβs fix this so that only articles in the specified category are retrieved.
Filtering queries with Prismaβs where
option
Section titled βFiltering queries with Prismaβs where optionβ-
Open the
app/routes/news.$category.tsx
file. -
Letβs start by renaming
allArticles
to something more suitable:app/routes/news.$category.tsx export async function loader({ params }: LoaderFunctionArgs) {const { category } = paramsinvariant(typeof category === 'string', 'Category not found')const allArticles = await prisma.article.findMany({const filteredArticles = await prisma.article.findMany({select: {id: true,title: true,category: { select: { name: true } },images: { select: { id: true } },},})return json({ category, allArticles })return json({ category, filteredArticles })} -
Next, we need to actually implement the filtering logic.
Weβll use Prismaβs
where
option to filter articles bycategory
. -
Filter articles by
Section titled βFilter articles by categoryβcategory
We already have access to the
category
parameter, so letβs add awhere
option to our query:app/routes/news.$category.tsx export async function loader({ params }: LoaderFunctionArgs) {const { category } = paramsinvariant(typeof category === 'string', 'Category not found')const categoryTitle = toTitleCase(category)const filteredArticles = await prisma.article.findMany({where: {category: {slug: category, // Retrieves only articles in the specified category},},select: {id: true,title: true,category: { select: { name: true } },images: { select: { id: true } },},})return json({ categoryTitle, filteredArticles })} -
Update
Section titled βUpdate useLoaderData with filteredArticlesβuseLoaderData
withfilteredArticles
Finally, we need to update the
useLoaderData
hook in ourNewsIndexPage
component to return thefilteredArticles
data, andmap
through this in place of the oldallArticles
array:app/routes/news.$category.tsx export default function NewsCategoryPage() {const { category, filteredArticles } = useLoaderData<typeof loader>()return (<div className="container py-8 lg:py-16"><h2 className="mb-16 text-h2">{category}</h2><div className="grid grid-cols-1 gap-6 md:grid-cols-4 xl:grid-cols-3">{filteredArticles.map(article => {return (<ArticleCardkey={article.id}title={article.title}categoryTitle={categoryTitle}imageId={article.images[0]?.id}/>)})}</div></div>)} -
Check filters in the browser
Section titled βCheck filters in the browserβNow, if you navigate to the news index page and click on a category, you should see the articles update based on the selected category:
Summary
Section titled βSummaryβIn this guide, we have:
- Learned about the
where
option in Prisma to filter database records based on specific criteria. - Updated the
loader
function in ourapp/routes/news.$category.tsx
file to filter articles by category and if they are published or not. - Updated the
useLoaderData
hook in ourNewsIndexPage
component to return thefilteredArticles
data and map through this in place of the oldallArticles
array. - Checked the filters in the browser to ensure they are working as expected.
- Further enhanced the news index page.
Whatβs next?
Section titled βWhatβs next?βIn the next guide, we will add an extra page to display the content of individual articles.