User is possibly bull (9-Updating Data - lecture)

image

I am getting this error message : ‘user’ is possibly 'null" for PUT request:

const updatedUser = await prisma.user.update({
where: { id: user.id },
data: {
name: body.name,
email: body.email,
},
});

Here is my code:

export async function PUT(
request: NextRequest,
{ params }: { params: { id: string } }
) {

const body = await request.json();

const validation = schema.safeParse(body);

if (!validation.success)
return NextResponse.json(validation.error.errors, { status: 400 });

const user = await prisma.user.findUnique({
where: { id: parseInt(params.id) },
});

if (user)
return NextResponse.json({ error: “User not found” }, { status: 404 });

const updatedUser = await prisma.user.update({
where: { id: user.id },
data: {
name: body.name,
email: body.email,
},
});

return NextResponse.json(updatedUser);
}

My bad , I found the error, I should check for → if (!user).

Thanks

1 Like

First off – great job finding the bug.

Secondly – Thank you for not deleting the topic. It might help others. :slight_smile: