Full crud request examples & best practices for t3/trpc/react-query?
I've been struggling attaining trpc/react-query/prisma nirvana because my brain just can't seem to grok what's happening between the different technologies.
I come from a Ruby on Rails background, so I'm used to thinking about making skinny controllers and fat models. This inherently is difficult for me to grasp if I should be building out logic in my api/server/router for each Model, or if I should be building functional components that do specific things with the data I need, like, return results that match chained filters.
I guess my biggest question is "Should I think of queries that return data or manipulate data as components, logic that should be abstracted into a hook, or logic that should be coded into routers?"
I hope that even makes sense...I've tried watching a bunch of t3-specific youtube tutorials to understand some of the patterns used, however I'm still struggling because most of this information is for just react-query and no use of TRPC.
Can anyone share some best practices/patterns for basic CRUD operations specifically with the T3 stack for reference?
I really don't want to drop TRPC and just use vanilla react-query with fetch since the benefits of type safety are important to my use case.
I really don't want to drop TRPC and just use vanilla react-query with fetch since the benefits of type safety are important to my use case.
2 Replies
First of all, tRPC is using react-query for the client.
Regarding CRUD:
I like to think of tRPC queries/mutations of just functions that run on the backend but give the result back to the client. So, specific functions for the use case you have in a client component.
This is different to the classic REST-like CRUD operations where a single entity is the focus of a route. While you can of course build a REST-like CRUD API and use classic REST patterns, you are free to use tRPC how you like.
My tip:
Get started. Use tRPC in a "functions that run on the backend but give the result back to the client" mindset, i.e. treat it like any other function, and see how that works for you.
You are completely free to use tRPC however you like and what the features you are building actually need.
One other thing: The query and mutation difference is just - queries' are cacheable, mutations are not. Anything else confused me before I made that distinction.
tRPC and React Query are just a way to make http requests, with caching and invalidation in the frontend. They don't demand anything specific in terms of how you architect your app. I tend to default to doing logic on the server with specialized endpoints, but i know there are people as well who write basic CRUD endpoints and then refine using complex hooks that handle large parts of application logic.
"best practices" is kind of a silly concept, nobody can agree on this stuff, just do what you / your team thinks will keep the project maintainable