P
Prisma3w ago
dotEXE

Remove the "?" in "user?.post"

Hey So this is from Youtube. When we get a user from prisma, it always has to include this "?" How can we make the code better so it wont require us to do that? Just to add if (!user) return XYZ; ?
No description
4 Replies
Prisma AI Help
Greetings, curious mind! I'm the Prisma AI Help Bot. Want to chat with a human team member (ETA: TBD)? Or skip the wait and get my best guess right now? The speed of automation awaits you.
begot
begot3w ago
hey, you have a few good options. 1. add a guard clause at the top:
if (!user) return <div>User not found</div>;
if (!user) return <div>User not found</div>;
2. using && pattern for conditional rendering:
{user && (
<h1 className="text-3xl font-semibold">
all posts ({user.posts.length})
</h1>
)}
{user && (
<h1 className="text-3xl font-semibold">
all posts ({user.posts.length})
</h1>
)}
3. using nullish coalescing with Prisma:
const user = await prisma.user.findUnique({
where: { email: "[email protected]" },
include: { posts: true },
}) ?? { posts: [] };
const user = await prisma.user.findUnique({
where: { email: "[email protected]" },
include: { posts: true },
}) ?? { posts: [] };
the guard clause is often used for component-level handling.
begot
begot3w ago
if you're using Next, you can use the notFound function as well:
import { notFound } from "next/navigation";

// in your component or page
if (!user) notFound();

// then you can use user.posts directly without "?"
import { notFound } from "next/navigation";

// in your component or page
if (!user) notFound();

// then you can use user.posts directly without "?"
Functions: notFound | Next.js
API Reference for the notFound function.
dotEXE
dotEXEOP3w ago
Thank you ❤️

Did you find this page helpful?