Skip to content

Display published articles

Now that we’ve implemented the functionality to publish and unpublish articles, we need to modify the home page and /article/$articleId routes to display only published articles.

Open the file at app/routes/_index.tsx and remind yourself of the code we wrote to fetch all articles:

app/routes/_index.tsx
9 collapsed lines
import { type MetaFunction } from '@remix-run/node'
import { json, Link, useLoaderData } from '@remix-run/react'
import heroImage from '~/assets/jpg/sample-hero.jpg'
import { Button } from '~/components/atoms/Button.tsx'
import ArticleCard from '~/components/organisms/ArticleCard.tsx'
import HeroCallToAction from '~/components/organisms/Hero/HeroCallToAction.tsx'
import { prisma } from '~/utils/db.server.ts'
export const meta: MetaFunction = () => [{ title: 'Epic News' }]
export async function loader() {
const allArticles = await prisma.article.findMany({
select: {
id: true,
title: true,
category: { select: { name: true } },
images: { select: { id: true } },
},
})
return json({ allArticles })
}
45 collapsed lines
export default function Index() {
const { allArticles } = useLoaderData<typeof loader>()
return (
<main>
<HeroCallToAction
image={heroImage}
imageRight={true}
hasBackgroundColour={true}
>
<div className="flex h-full flex-1 flex-col justify-between p-16">
<div className="flex flex-col gap-8">
<h2 className="text-h2">Welcome to Epic News</h2>
<p className="text-lg">
Keep up to date with the latest tech news.
</p>
</div>
<Button asChild variant="default" size="lg">
<Link to="/signup">Sign up</Link>
</Button>
</div>
</HeroCallToAction>
<div className="container py-16">
<h2 className="mb-8 text-h2 font-normal">Latest news</h2>
<div className="grid grid-cols-2 gap-6 md:grid-cols-3 lg:grid-cols-4">
{allArticles.length > 0 ? (
allArticles.map(article => (
<ArticleCard
key={article.id}
articleId={article.id}
title={article.title}
category={article.category?.name}
imageId={article.images[0]?.id}
/>
))
) : (
<p>No articles found</p>
)}
</div>
</div>
</main>
)
}

Although the articles are now filtered on the home page, the /news/$category and /article/$articleId routes still display all articles, regardless of whether they are published or not.

With these changes in place, your homepage, /news/$category, and /article/$articleId routes should now display only published articles.

In this step, we have:

  • Modified the homepage, /news/$category, and /article/$articleId routes to display only published articles.
  • Added a fallback UI to display a message when no published articles are found in a category.