T3 Stack Tutorial - Posts won't retain

Hello! I am new here and new to TS and React. I am attempting to follow along with Theo's amazing T3 stack tutorial but have been running into an issue I was hoping someone would be able to assist with. Upon running the app, I keep getting the error: prisma:query SELECT trilldb.Post.id, trilldb.Post.createdAt, trilldb.Post.content, trilldb.Post.authorId FROM trilldb.Post WHERE 1=1 ORDER BY trilldb.Post.createdAt DESC LIMIT ? OFFSET ? ❌ tRPC failed on posts.getAll: Cannot read properties of undefined (reading 'users') Ultimately what keeps happening is the posts won't retain on the app side but on the Prisma side they are.. Any suggestions? I can provide further context, but does anyone have a quick solution for how they resolved this issue? I've tried searching online/stack overflow but to no avail.
64 Replies
thevalorised
thevalorised16mo ago
We might need to see the implementation of the router that calls posts.getAll and how it is called on the frontend but it can simply be a db mismatch issue. Make sure you have your schema file right, sync the db and generate types with npx prisma db push, and check if data actually exists on db with npx prisma studio
lil_bixbyte
lil_bixbyte16mo ago
Thank you for the suggestion. Unfortunately the issue persists. What's happening is the post data exists on the db but I keep getting errors on the application and it just says "Something went wrong" instead of posting. I can post emojis but there is no record being maintained on the application.
meeepsss
meeepsss16mo ago
could you post your schema and the actual code which is failing?
lil_bixbyte
lil_bixbyte16mo ago
Here is the schema
lil_bixbyte
lil_bixbyte16mo ago
Here is the code if you don't want to download:
datasource db {
provider = "mysql"
url = env("DATABASE_URL")
relationMode = "prisma"
}

generator client {
provider = "prisma-client-js"
}

model Post {
id String @id @default(cuid())
createdAt DateTime @default(now())

content String @db.VarChar(255)
authorId String

@@index([authorId])
}
datasource db {
provider = "mysql"
url = env("DATABASE_URL")
relationMode = "prisma"
}

generator client {
provider = "prisma-client-js"
}

model Post {
id String @id @default(cuid())
createdAt DateTime @default(now())

content String @db.VarChar(255)
authorId String

@@index([authorId])
}
meeepsss
meeepsss16mo ago
could you wrap the code in ``` nvm that's all fine do you know the code which is failing
lil_bixbyte
lil_bixbyte16mo ago
As for what's failing, that is hard for me to determine. The following files have errors, but they all have to do with "Unsafe assignment of an any value" : 1. /src/pages/[slug].tsx 2. /src/pages/post/[id].tsx 3. /server/api/routers/posts.tsx 4. /components/postview.tsx 5. /server/api/helpers/filterUserForClients.ts 6. /server/api/helpers/ssgHelper.ts The error code that is being thrown is mentioned in the body of the original post. There is another error code that actually occurs when I post which I can add as well
meeepsss
meeepsss16mo ago
show me your posts.getAll query? yeah sure you shouldn't have all those TS errors btw. Using TS isn't going to help much if you don't type things :p
lil_bixbyte
lil_bixbyte16mo ago
Here is the error that I just got when posting an emoji:
prisma:query BEGIN
prisma:query INSERT INTO `trilldb`.`Post` (`id`,`createdAt`,`content`,`authorId`) VALUES (?,?,?,?)
prisma:query SELECT `trilldb`.`Post`.`id`, `trilldb`.`Post`.`createdAt`, `trilldb`.`Post`.`content`, `trilldb`.`Post`.`authorId` FROM `trilldb`.`Post` WHERE `trilldb`.`Post`.`id` = ? LIMIT ? OFFSET ?
prisma:query COMMIT
prisma:query SELECT `trilldb`.`Post`.`id`, `trilldb`.`Post`.`createdAt`, `trilldb`.`Post`.`content`, `trilldb`.`Post`.`authorId` FROM `trilldb`.`Post` WHERE 1=1 ORDER BY `trilldb`.`Post`.`createdAt` DESC LIMIT ? OFFSET ?
❌ tRPC failed on posts.getAll: Cannot read properties of undefined (reading 'users')
prisma:query SELECT 1
prisma:query SELECT `trilldb`.`Post`.`id`, `trilldb`.`Post`.`createdAt`, `trilldb`.`Post`.`content`, `trilldb`.`Post`.`authorId` FROM `trilldb`.`Post` WHERE 1=1 ORDER BY `trilldb`.`Post`.`createdAt` DESC LIMIT ? OFFSET ?
❌ tRPC failed on posts.getAll: Cannot read properties of undefined (reading 'users')
prisma:query SELECT `trilldb`.`Post`.`id`, `trilldb`.`Post`.`createdAt`, `trilldb`.`Post`.`content`, `trilldb`.`Post`.`authorId` FROM `trilldb`.`Post` WHERE 1=1 ORDER BY `trilldb`.`Post`.`createdAt` DESC LIMIT ? OFFSET ?
❌ tRPC failed on posts.getAll: Cannot read properties of undefined (reading 'users')
prisma:query SELECT `trilldb`.`Post`.`id`, `trilldb`.`Post`.`createdAt`, `trilldb`.`Post`.`content`, `trilldb`.`Post`.`authorId` FROM `trilldb`.`Post` WHERE 1=1 ORDER BY `trilldb`.`Post`.`createdAt` DESC LIMIT ? OFFSET ?
❌ tRPC failed on posts.getAll: Cannot read properties of undefined (reading 'users')
prisma:query BEGIN
prisma:query INSERT INTO `trilldb`.`Post` (`id`,`createdAt`,`content`,`authorId`) VALUES (?,?,?,?)
prisma:query SELECT `trilldb`.`Post`.`id`, `trilldb`.`Post`.`createdAt`, `trilldb`.`Post`.`content`, `trilldb`.`Post`.`authorId` FROM `trilldb`.`Post` WHERE `trilldb`.`Post`.`id` = ? LIMIT ? OFFSET ?
prisma:query COMMIT
prisma:query SELECT `trilldb`.`Post`.`id`, `trilldb`.`Post`.`createdAt`, `trilldb`.`Post`.`content`, `trilldb`.`Post`.`authorId` FROM `trilldb`.`Post` WHERE 1=1 ORDER BY `trilldb`.`Post`.`createdAt` DESC LIMIT ? OFFSET ?
❌ tRPC failed on posts.getAll: Cannot read properties of undefined (reading 'users')
prisma:query SELECT 1
prisma:query SELECT `trilldb`.`Post`.`id`, `trilldb`.`Post`.`createdAt`, `trilldb`.`Post`.`content`, `trilldb`.`Post`.`authorId` FROM `trilldb`.`Post` WHERE 1=1 ORDER BY `trilldb`.`Post`.`createdAt` DESC LIMIT ? OFFSET ?
❌ tRPC failed on posts.getAll: Cannot read properties of undefined (reading 'users')
prisma:query SELECT `trilldb`.`Post`.`id`, `trilldb`.`Post`.`createdAt`, `trilldb`.`Post`.`content`, `trilldb`.`Post`.`authorId` FROM `trilldb`.`Post` WHERE 1=1 ORDER BY `trilldb`.`Post`.`createdAt` DESC LIMIT ? OFFSET ?
❌ tRPC failed on posts.getAll: Cannot read properties of undefined (reading 'users')
prisma:query SELECT `trilldb`.`Post`.`id`, `trilldb`.`Post`.`createdAt`, `trilldb`.`Post`.`content`, `trilldb`.`Post`.`authorId` FROM `trilldb`.`Post` WHERE 1=1 ORDER BY `trilldb`.`Post`.`createdAt` DESC LIMIT ? OFFSET ?
❌ tRPC failed on posts.getAll: Cannot read properties of undefined (reading 'users')
meeepsss
meeepsss16mo ago
yeah there's no way to tell anything from that. It's just showing prisma's prepared statements are you sure the db is properly populated (check with prisma studio)? Otherwise, you're going to need to send some code ie posts.getAll for a start
lil_bixbyte
lil_bixbyte16mo ago
I'm running prisma studio, and the posts are all being recorded there
lil_bixbyte
lil_bixbyte16mo ago
lil_bixbyte
lil_bixbyte16mo ago
This is what I get on the app though:
lil_bixbyte
lil_bixbyte16mo ago
lil_bixbyte
lil_bixbyte16mo ago
I noticed there were a few things that were depracated that Theo was using in the video and I am super duper new to TS so a lot of this stuff goes way over my head. I figured this would just be a good way to throw myself into the deep end.. 😄 I really appreciate your help, meeps
meeepsss
meeepsss16mo ago
could you send a screenshot of any errors in the console yeah that looks good still need to see this trpc procedure
lil_bixbyte
lil_bixbyte16mo ago
My build is failing in Vercel. Here is the errors list:
Failed to compile.
./src/server/helpers/ssgHelper.ts
Module not found: Package path ./server is not exported from package /vercel/path0/node_modules/@trpc/react-query (see exports field in /vercel/path0/node_modules/@trpc/react-query/package.json)
https://nextjs.org/docs/messages/module-not-found
Import trace for requested module:
./src/pages/[slug].tsx
> Build failed because of webpack errors
Error: Command "npm run build" exited with 1
Failed to compile.
./src/server/helpers/ssgHelper.ts
Module not found: Package path ./server is not exported from package /vercel/path0/node_modules/@trpc/react-query (see exports field in /vercel/path0/node_modules/@trpc/react-query/package.json)
https://nextjs.org/docs/messages/module-not-found
Import trace for requested module:
./src/pages/[slug].tsx
> Build failed because of webpack errors
Error: Command "npm run build" exited with 1
meeepsss
meeepsss16mo ago
hmm not sure how to interpret that one..
lil_bixbyte
lil_bixbyte16mo ago
Here's the console:
lil_bixbyte
lil_bixbyte16mo ago
meeepsss
meeepsss16mo ago
cool ok, and the procedure?
lil_bixbyte
lil_bixbyte16mo ago
ngl I don't know what that means Here's what happens when I do a post:
lil_bixbyte
lil_bixbyte16mo ago
lil_bixbyte
lil_bixbyte16mo ago
You want me to expand any of these Objects?
meeepsss
meeepsss16mo ago
expand the getAll one i mean the code where you implemented posts.getAll in the trpc router
lil_bixbyte
lil_bixbyte16mo ago
lil_bixbyte
lil_bixbyte16mo ago
meeepsss
meeepsss16mo ago
yeah you've got to send the posts.getAll code it'll probably be in a file in server/api/routers
lil_bixbyte
lil_bixbyte16mo ago
import { clerkClient } from "@clerk/nextjs";
import { type User } from "@clerk/nextjs/dist/server";
import { TRPCError } from "@trpc/server";
import { Ratelimit } from "@upstash/ratelimit";
import { Redis } from "@upstash/redis";
import { z } from "zod";
import { createTRPCRouter, privateProcedure, publicProcedure } from "~/server/api/trpc";

const filterUserForClient = (user: User) => {
return {
id: user.id,
username: user.username,
profileImageUrl: user.profileImageUrl,
};
};

// Create a new ratelimiter, that allows 3 requests per 1 minute
const ratelimit = new Ratelimit({
redis: Redis.fromEnv(),
limiter: Ratelimit.slidingWindow(3, "1 m"),
analytics: true
});

export const postsRouter = createTRPCRouter({
getAll: publicProcedure.query(async ({ ctx }) => {
const posts = await ctx.prisma.post.findMany({
take: 100,
orderBy: [{ createdAt: "desc" }],
});

const users = (
await clerkClient.users.getUserList({
userId: posts.map((post) => post.authorId),
limit: 100,
})
).map(filterUserForClient);

console.log(users);
import { clerkClient } from "@clerk/nextjs";
import { type User } from "@clerk/nextjs/dist/server";
import { TRPCError } from "@trpc/server";
import { Ratelimit } from "@upstash/ratelimit";
import { Redis } from "@upstash/redis";
import { z } from "zod";
import { createTRPCRouter, privateProcedure, publicProcedure } from "~/server/api/trpc";

const filterUserForClient = (user: User) => {
return {
id: user.id,
username: user.username,
profileImageUrl: user.profileImageUrl,
};
};

// Create a new ratelimiter, that allows 3 requests per 1 minute
const ratelimit = new Ratelimit({
redis: Redis.fromEnv(),
limiter: Ratelimit.slidingWindow(3, "1 m"),
analytics: true
});

export const postsRouter = createTRPCRouter({
getAll: publicProcedure.query(async ({ ctx }) => {
const posts = await ctx.prisma.post.findMany({
take: 100,
orderBy: [{ createdAt: "desc" }],
});

const users = (
await clerkClient.users.getUserList({
userId: posts.map((post) => post.authorId),
limit: 100,
})
).map(filterUserForClient);

console.log(users);
return posts.map((post) => {

const author = users.find((user) => user.id === post.authorId);

if (!author?.username)
throw new TRPCError({
code: "INTERNAL_SERVER_ERROR",
message: "Could not find author for post",
});


return {
post,
author: {
...author,
username: author.username,
},
};
});
}),

create: privateProcedure.input(
z.object({
content: z.string().emoji("Only enojis are allowed").min(1).max(280),
})
)
.mutation(async ({ ctx, input }) => {
const authorId = ctx.userId;

const { success } = await ratelimit.limit(authorId);

if (!success) {
throw new TRPCError({
code: "TOO_MANY_REQUESTS",
message: "You have made too many requests",
});
}

const post = await ctx.prisma.post.create({
data: {
authorId,
content: input.content,
},
});

return post;
}),
});
return posts.map((post) => {

const author = users.find((user) => user.id === post.authorId);

if (!author?.username)
throw new TRPCError({
code: "INTERNAL_SERVER_ERROR",
message: "Could not find author for post",
});


return {
post,
author: {
...author,
username: author.username,
},
};
});
}),

create: privateProcedure.input(
z.object({
content: z.string().emoji("Only enojis are allowed").min(1).max(280),
})
)
.mutation(async ({ ctx, input }) => {
const authorId = ctx.userId;

const { success } = await ratelimit.limit(authorId);

if (!success) {
throw new TRPCError({
code: "TOO_MANY_REQUESTS",
message: "You have made too many requests",
});
}

const post = await ctx.prisma.post.create({
data: {
authorId,
content: input.content,
},
});

return post;
}),
});
That's the /server/router/posts.ts file
meeepsss
meeepsss16mo ago
const users = ( await clerkClient.users.getUserList({ userId: posts.map((post) => post.authorId), limit: 100, }) ).map(filterUserForClient); console.log(users); here you console.log users. This code should run right before the error - can you see what's logged for users in the console?
lil_bixbyte
lil_bixbyte16mo ago
I don't see anything like that. The first thing that hits the console is posts.getAll query
lil_bixbyte
lil_bixbyte16mo ago
meeepsss
meeepsss16mo ago
remember this code is running on the server so you wouldn't get anything on the client
lil_bixbyte
lil_bixbyte16mo ago
Ohhhhhh so should I be on the Prisma Studio end then
meeepsss
meeepsss16mo ago
you need to look in the console where you have npm run dev command running that will show you the logs
lil_bixbyte
lil_bixbyte16mo ago
Yeah that is where I'm pulling this from
meeepsss
meeepsss16mo ago
that's the browser console
lil_bixbyte
lil_bixbyte16mo ago
You mean the terminal?
meeepsss
meeepsss16mo ago
you need to look in the terminal window
lil_bixbyte
lil_bixbyte16mo ago
meeepsss
meeepsss16mo ago
the browser only gets the client's errors. You can see it's saying internal server error - the error happened on the server. You're calling posts.getAll which runs on the server through the api directory (managed by trpc) yep so it's failing on this: const users = ( await clerkClient.users.getUserList({ userId: posts.map((post) => post.authorId), limit: 100, }) ).map(filterUserForClient); put another console.log on the line before with something like console.log('before the troublesome line') and see if that gets logged in the server terminal
lil_bixbyte
lil_bixbyte16mo ago
lil_bixbyte
lil_bixbyte16mo ago
Alright so that code chunk is the issue then? That's where it's complaining in VS code as well
lil_bixbyte
lil_bixbyte16mo ago
lil_bixbyte
lil_bixbyte16mo ago
Here is what the error is stating when I hover over it:
lil_bixbyte
lil_bixbyte16mo ago
meeepsss
meeepsss16mo ago
i haven't watched the video but the thing to do now is to make sure you've copied it correctly (there's probably an example repo)
lil_bixbyte
lil_bixbyte16mo ago
...Yeah I totally did that already
meeepsss
meeepsss16mo ago
and probably go through and figure out where all your TS errors are coming from. Hopefully fixing those one by one will help you debug the issue for instance, your clerkClient.users shouldn't have an any type
lil_bixbyte
lil_bixbyte16mo ago
That's what the actual video and repo used though...
meeepsss
meeepsss16mo ago
i mean the typescript errors elsewhere too. You said they're spread across the project
lil_bixbyte
lil_bixbyte16mo ago
Yeah they are but they all seem to be that "any" issue
lil_bixbyte
lil_bixbyte16mo ago
lil_bixbyte
lil_bixbyte16mo ago
lil_bixbyte
lil_bixbyte16mo ago
They all look like this, and the only quick solution is to Disable both @typescript-eslint/no-unsafe-member-access and @typescript-eslint/no-unsafe-assignment
meeepsss
meeepsss16mo ago
if you're getting the same error a bunch, you've got to look into them one of those warnings is probably the cause of the issue!
lil_bixbyte
lil_bixbyte16mo ago
Alright I'm digging I'll let you know if I strike any gold
meeepsss
meeepsss16mo ago
awesome. Best of luck it's definitely important to get the fundamental stuff down like TS and understanding what's server vs client in next t3 has a bunch of stuff to solve problems which you probably haven't seen in practice before. Without understanding the motivations of these packages, it's hard to figure out how they work jumping in is great but maybe jump in on TS and next project first if you keep having difficulties :p tag me if you figure something out or get stuck though
lil_bixbyte
lil_bixbyte16mo ago
Thank you so much, meeps. Are there any recommended platforms or learning articles you use? Really all I've used is Codecademy to learn code
meeepsss
meeepsss16mo ago
this course is good for very quickly starting TS https://www.totaltypescript.com/tutorials/beginners-typescript
Total TypeScript
Beginner's TypeScript Tutorial
Free interactive video tutorial that will help you get started with TypeScript.
meeepsss
meeepsss16mo ago
i always suggest YDKJS as they're free to read books which are great (if a little outdated in patterns now)
meeepsss
meeepsss16mo ago
GitHub
You-Dont-Know-JS/README.md at 1st-ed · getify/You-Dont-Know-JS
A book series on JavaScript. @YDKJS on twitter. Contribute to getify/You-Dont-Know-JS development by creating an account on GitHub.
meeepsss
meeepsss16mo ago
but those are probably not the best if you're more practically minded i learn from books initially so can't suggest much else. I'm sure lots of others have experience with learning JS more practically as for next, their documentation is good. Just take it slow and relate things back to simple example apps
lil_bixbyte
lil_bixbyte16mo ago
Sweet, I appreciate it, meeps. I'm definitely going to look into these. Also, I'll let you know if/when I find the solution. You're the best.
Want results from more Discord servers?
Add your server