Why does typescript change the type of user whenever I add this to my return function?
Hi guys, I am trying to understand this about typescript/trpc. Why does the type here keep changing? Why is it not accepting me to type user.data.... ?
46 Replies
share your code in a sandbox
it's very hard to help without full context
alternatively, cut and paste the relevant code into discord using code syntax:
or at the very least don't post screenshots where your code is almost entirely covered by an error or type resolution 🙂
Seems like you’re trying to access react query inside trpc router
You don't run queries inside a query.
Yeah what Captain said.
Oh...
That would be very good if I could do that
No... Just? Make your code reusable.
What do you mean? I was meaning to make it reusable. Make one query, and then I can reuse it inside other queries
But apparently that's not ideal
You can use middleware
Middlewares | tRPC
You are able to add middleware(s) to a procedure with the t.procedure.use() method. The middleware(s) will wrap the invocation of the procedure and must pass through its return value.
Sorry about the screenshots. Next time I will share it by pasting the code
Or the simple good old function that you use both places
Or 1965's copy paste.
Interesting. Middlewares...
if you find yourself wanting to communicate between multiple routers, chances are you might want to go learn about software architecture patterns
specifically layered architecture
I don't know your use case, but a common one is the repository pattern
having some code abstracted away into a repository that is then reused by multiple services (or in trpc, routers)
instead of having services communicate with each other directly. Imo, that's an anti pattern with tRPC (unless you're doing integration testing specifically, then you can use https://trpc.io/docs/server-side-calls)
I just felt that I didn't want to always use ctx.prisma.user.findUniqueI() everytime I wanted to get the user object from db. I made this middleware for me to have the user object. Would this be ok?
That being said, it would do a SQL call every single protected procedure, which might be suboptimal
And slow down the service for when I don't need to call prisma
middlewares are great for code reuse, but keep in mind they run all the time for the procedures you apply them to.
if you want to reuse some code in the middle of some arbitrary procedure, they're not as ergonomic to work with.
in that case you're better off just creating a function
Make a different procedure