Great point, but his example makeRequest function that he was replacing as a POST request, so the useMutation hook is what should be used instead of that. However yes, the terminology being used is confusing - for getting/fetching data, you would usually use a GET request, or if using react query, you might use the useQuery hook. That being said, there are cases where it's acceptable to use a POST request to fetch data.
react query has a hook called useQuery which is the one to use for fetching data. useMutate is supposed to be used only for mutating/changing data, ie create/edit/delete.
Exactly..… he should have used useQuery on the client and use the await prefetchQuery on the server component and wrap the component consuming the data in a hydration boundary
_Look at this sublte inclusion of type safety , the tasteful thickness of it._ *Oh my god!* _It even has the loading and error states handled by react-query._
@@joshtriedcoding how long has your channel been up? It seems like you've just discovered react-query and talking about it like it's something incredible. It's silly and funny at the same time (I think that's what the guy was trying to say, it's called sarcasm)
Hi Josh. My main problem with this approach is data consumption and download speed / execution time, which may or may not be a concern depending on where you operate. I'm currently working for a client in Zambia and Malawi which is known for their expensive data and lack of network availability, so everything counts. As a test, I made both server action and /api route return the same payload ({foo:"bar"}}, both using POST (a restriction of server actions) and there are the results: - server actions - 447B download size - 84ms to respond - /api/ route - 192B download size - 25ms to respond As the request in server actions points to the route itself it's likely running much more code than the /api route which just returns some JSON. That said 100% agree this is a much better DX with types flowing through and love to see new and creative approaches to current problems!
Mutations are meant to be used for creating or altering data -- i.e to mutate it., not for fetching data. Fetching data should use useQuery. POST, PATCH, PUT requests should use useMutation.
Amazing! Thanks to this video I went from Apprentice Brick Layer to Senior-Seasoned Full-Stackoverflow-BackToFront-End Devengineer and ready for retirement.
instead of using react-query I would just implement a custom hook for the project that reduce redundancy and track request state. You can make it typed for typescript easily with a generic function, like
This is great, I’ve been using this. Once you need to protect the mutations, schema validation or some kind of middleware, I’ve found trpc to be the best option. You can call trpc mutations in server actions. If you’re not using react query, then next-safe-action is a good choice
Sometimes you want to perform a GET request when a user clicks a button for example. You can't really control when a useQuery runs unless you specify the enabled property
@@outis99 There are ways to do that from query (if i'm not mistaken). useQuery exports a "refetch" function for that. We can also invalidate the specific query key using queryClient (useQueryClient). And there might be other ways. I might not be right about this, but as far as i know, mutate are intended for post, put, etc. If anyone has a deeper understanding about react-query, i'm here to learn :D
@@StabilDEV I guess what he means is that with useQuery the query performs when the component is mounted and if yout want to controll it yout need to pass the enabled property and use refetch but with useMutation you just need to use the mutate function.
@@josepazmino842 yes, but the reason hes using useMutation is not for this reason. Like Stabildev said, all server actions are post so you can't use useQuery.
You can also add a type to the useMutation like useMutation It seems like the reason this works in the video is because typescript can infer the types from the getUser function you defined. Still a nice pattern! Thanks for sharing!
server actions are not made for fetching data, for this case better use "server only", (it is not provided by default). Basically you can achieve the same using native fetch and built in loading, suspense, error boundary. The big difference is because you use a hook, you are not more purely on server side, this require directive "use client", but your approach is much cleaner.
I am still not fond of writing back-end code with Next.js. I simply do not see it becoming manageable as the project grows in size and complexity. It seems to be more suitable for a small-scale project, such blogging, with minimal logic, where using a large-scale framework, such as .NET or Spring Boot, would indeed be an overkill. Furthermore, I followed the official tutorial from Next.js' website and there they even wrote SQL code, an approach that reminded me of when I started learning how to code with PHP, and I would write SQL, PHP, and HTML all together. It was about 10 years ago or so. A simple CRUD, tops.
Unlike queries, mutations are typically used to create/update/delete data or perform server side-effects. For this purpose, TanStack Query exports a useMutation hook. That from react-query documentation
I guess the only "drawback" is that it only works in client components, since it's a hook. But still a pretty great solution, I absolutely love react query!
@@redeemr does this mean you must maintain the same tags on the Tanstack Query side and Server Actions? How does this look in practice, to minimize the need to manage 2 caches?
@@teeldinho471 Well, you could just not use Next.js cache, passing "no-store" to your fetchs or using some lib that doesn't depend on fetch like Axios to make requests.
I found setting up TRPC a nightmare with inadequate documentation, so I’ve just been exporting/importing types all this while. But this is actually a killer combo - thank you so much!
I fucking love you, been stuck with fetching api because of cors or wtf that was and the route method was not working, decided to sleep, after 4 hours and BAM in the morning watched your vid and it worked, ty,
woah thanks Josh for sharing this incredible technique for fetching data way easier than creating api routes, Im already tired of doing bunch of routes lol.
Hey Josh, I definitely like this approach but the NEXT team are saying "handle form submissions and data mutations" and i have seen around the internet to not to use for as "GET" use only as Mutation function and so, What are your thoughts on this. Is it really a thing to use only as a Mutation or we can do whatever inside it without worrying about these things?
I’ve tried using actions for getting data. Went back to using usual fetch. Reason? Server actions are executed sequentially, they can not run in parallel. And any other user interaction will be blocked until action is done. This has a huge impact on performance😕 Also, POST requests don’t really have the caching benefits of GET requests
Tan stack query hooks actually do a pretty good job inferring types, in some special cases you might need to pass generic parameters for type safety, but you can definitely use them without the server action combination.
Do you typically separate out your server actions into separate files or just include them all in an "actions.ts" file? I'm curious how you prefer to structure your files/folders in general, I'd love to see a video on that at some point!
Also interested. Currently I have my actions in /server/actions with each being grouped somehow if possible. Grouped based on table names or something. But I've seen one file and I've seen a single actions.ts in the same directory as the page using that action
I like the idea, but why would you use a mutation function to get data? Why not use the useQuery hook to get the data in that example? Apart from that the idea is very good!
@@fitimbytyci345 You're doing it right in this case, but don't forget mutations when the data will be created/updated/deleted with users actions, it's easier to implement optimistic updates with it.
Didn't know react query works with server actions, that's great! Only downside is, server actions are always POST, which doesn't make much sense. I mean, you can get data on the server, but if you're using react query and want to have any sort of dynamic loading going on, you'll still need GET endpoints for actual queries. I mean, maybe not *need*, but I refuse to ever fetch data with POST. I'd honestly stick to the default verbose server actions (maybe wrapped behind a custom hook) if only they stopped using FormData. That api has been growing on me, but I really don't want FormData.
This looks great! However, doesn't react query provide support for typescript using generic types? I personally love extracting every useState and useMutation with fetching logic into separate hook, which take as a parameter the query options object (which also has special type provided by react query), therefore making those hooks highly reusable across many different components due to their customizability.
yep its similar... server actions are simply auto-generated api routes, same as trpc. So in my opinion its just a less mature alternative. The only thing server actions have going for them is they are "native to the framework" and hence can do revalidateTag() and notify the client to do the router.refresh() equivalent automatically.
If by query options you mean the data, loading and error states, it won’t work in app router as actions are to be defined on server and hooks on the client
Hmm why tanstack query isn't typesafe (btw why use useMutation for plain fetching?) ? You can specify types for response where you set up your API handlers/ query functions (and by sharing type declaration across front and beckend you can get typesafety if you wnat/need across both project even if they are separate)
I think it's meant to be a post request but getUser is a bad example for that. Also like you said, you could just specify the data type returned by the fetch request as a typescript interface, so this seems like he's demonstrating a benefit that isn't actually a benefit unless he's assuming we are working with JavaScript and not TypeSrcipt I guess
But then you have to create your own types when the code is already giving you the types. This method gets the types from the code/libraries. However the downside of this method, like you mentioned, is it uses only post requests(server actions are only post req) which don't cache. If you want 'type safety' either use trpc, server components, or validate with zod. This is mostly a dx issue anyways, your method works fine if done properly.
If you want to know the type when using useQuery or useMutation, you can just define the type on that like useQuery() then data must be Response | undefined type so you dont need to use server action on that.
While not sure about react query, RTK query does give the ability to add types for both response types and query args with all the isLoading, error, etc states
Would you still use Mutation if the data needs to be loaded on the pageLoad? As per my understanding, mutations are generally used for CRUD operation with server and not really for data fetching.
Wow! I think this has the potential to eliminate the need for tRPC. That means zero configuration for Front and Back type-safety, and less bloated full-stack projects. It's amazing to say the least! 🔥
I mean that's by design, POST request shouldn't be used to GET a resource which I would expect to be cached Edit: saw the other comments and understood what you meant, yep bad approach
You can wrap ReactQuery hooks inside of your own custom hooks, then you can get type safety and any additional business logic, or statuses you need before returning to the page components. I will keeping using this pattern + api routes for now, still not seeing benefits from server actions, and it is a lot less intuitive to use.
This deserves a like ! I think you can use "use server" instead of functions, it would be nice if you can just export a custom hooks that can be re-used without thinking about importing different dependencies (similar to trpc)
Does this help with "protecting" an api key, so the user cannot just simply take it out of the network tab? If not, do you have any recommendations on how to implement client side actions like updating, deleting, etc. without exposing the token to the client?
I have a problem, if you want to handle errors, in Server action directly throw errors in development mode can, But in production mode the error message will be hidden, how to solve?
The problem is, that it‘s always a post-request. Isn‘t it better to use Hono/ElysiaJS in the API-route like you did in another video? I am trying ElysiaJS at the moment and the „eden treaty“ is amazing. You can use it in react-query and in react server components. This way you can use middleware and all other stuff, you are used to on api-servers. And it‘s easy to seperate them if needed.
what benefit does "use server" directive have in getUser function? what if instead of making it a server action we made it a normal function without "use server" directive?
What about server components, query inside metadata, HydrationBoundary and prefetch query, cache concerns between next/fetch and RQ? would be great if you could cover all fetching aspects :) All the best
If you don't need caching or invalidation you can even invoke the server action within a custom handler without using RTK mutations, but you have to set a custom loading state, which kinda sucks tho. Also there's some weird errors that occur on the form html element when using server actions directly on them, which is really annoying. So yeah. Invoking actions inside handlers/useEffect or simply react query is much more preferable.
I think that server actions are called sequentially and not in parallel by Next (since that is considered to be most appropriate for mutations). So, this pattern might introduce really bad client-server waterfalls and lead to poor performance.
This is excellent if you have project which is browser only, but if project get bigger, and mobile app is needed i think server actions might be problematic. Please correct me if im wrong.
For me there’s no reason to use such a big library like react-query just for data fetching, it has a lot more but for a simple fetch just use standard library. Dont overengineer and add a lot of complex to a simple fetch. btw, you could create your own hook (which you’ll write once and use it a Million times) and it may be more performant
It is suppose nodejs and js(frontend backend) work similarly then when both move to typescript safe type, it should too. but new framework dont copy old stuff that good. This kind of pattern already exist from 10 year ago from knockoutjs , emberjs etc. Because fullstack developer trend, we love js too much, we have good workflow. now in react, too much noise, and ppl dont care good small pattern.
Dislike the naming conventions, mutate != GET requests. The destructuring renaming adds mental overload for no reason. Using API routes is still OG in enterprise level apps imo
can i have someone opinion on my approach? like im using server actions for fetching data and in pages.tsx is server component which i use the server actions function, and im passing the data trough props to specific component inside page.tsx which all the components here is client side component. then rendering the data in this client side. is this a good approach? and with react-query could it run on server components?
Yes I do kinda the same. In page.tsx which is async I make a fetch request to retrieve data from db and then pass this data as props to a client component. For the second question I can't answer you because I use nextjs server actions and I'm happy with it for now.
This approach makes sense with mutations, but how would this work with fetching a query? afaik 'data' in useMutation works differently, it is "the last successfully resolved data for the mutation", and since it doesn't make sense to call 'mutate' on a query, how do you get the data? I would love to have a similar approach for simple GETs, that doesn't involve using server components and giving up on react-query and its loading state management
It works the same, with useQuery you pass a server action to the queryFn, the query will be called automatically when the component renders just like any query.
This is very handy BUT it comes with a very big catch: you can't abort server actions 🥶 And every issue/discussion about adding a way to cancel server action in the Next community has been ignored so far from what I have seen. Idk I used this all the time so far but I am starting to think that this should be classified as an anti-pattern, we should use "actions" for real actions, not to fetch data. From my experience tRPC is still the way to go and using server actions for fetching data with type-safety and without surprises along the way.
Pls someone tell me the right way to fetch data in server components. I currently fetch directly from my db on the server side but I noticed there’s no caching.
all this is nice, but we just not using useMutation as it is supposed to be used. (we have to mutate with useMutation) why just dont pass server action (that in your case gets data) to queryFn? const query = useQuery({ queryKey: ['todos'], queryFn: __your_server_action_getting_data__ }) and one more thing, even though it works server actions are idiomaticaly used basicaly like a post request (mutate data) - from documentation (not to get data) god knows if it is ok use it in production for now
Possible. Especially if used in combination with cookies for authentication so you can fetch the current session anywhere on the server. But also im realizing that server actions are executing sequentially and not in parallel. What do you think?
Who said that you can know the type returned by react query? you can pass a generic argument and it will use that as the fetched resource type on the data prop.
thank you josh , but i have another opinion i think no i will not use it , by this you are fetching data in client side , but in next the standard is fetching data in server components , the data fetching should be in the server , maybe we can find some good usecase but in general fetching data in server + skeleton components in loading file will be better in my opinion !
“mutate” isn’t intuitive because it wasn’t really meant for get requests it’s meant for creating and updating data.
exactly
useQuery is the hook for data fetching, useMutation is for... mutating.
Great point, but his example makeRequest function that he was replacing as a POST request, so the useMutation hook is what should be used instead of that. However yes, the terminology being used is confusing - for getting/fetching data, you would usually use a GET request, or if using react query, you might use the useQuery hook. That being said, there are cases where it's acceptable to use a POST request to fetch data.
react query has a hook called useQuery which is the one to use for fetching data. useMutate is supposed to be used only for mutating/changing data, ie create/edit/delete.
Exactly..… he should have used useQuery on the client and use the await prefetchQuery on the server component and wrap the component consuming the data in a hydration boundary
Impressive, very nice. Let's see Paul Allen's data fetching pattern.
_Look at this sublte inclusion of type safety , the tasteful thickness of it._ *Oh my god!*
_It even has the loading and error states handled by react-query._
@@entropysquare9683 something wrong, man? you're sweating
@@joshtriedcodingleave bro him bro. He just a sad little junior dev who’s trying to get some attention. Just keep doing great work ❤
@@joshtriedcoding how long has your channel been up? It seems like you've just discovered react-query and talking about it like it's something incredible. It's silly and funny at the same time (I think that's what the guy was trying to say, it's called sarcasm)
Can somebody explain the Paul Allen thing
Hi Josh. My main problem with this approach is data consumption and download speed / execution time, which may or may not be a concern depending on where you operate. I'm currently working for a client in Zambia and Malawi which is known for their expensive data and lack of network availability, so everything counts. As a test, I made both server action and /api route return the same payload ({foo:"bar"}}, both using POST (a restriction of server actions) and there are the results:
- server actions
- 447B download size
- 84ms to respond
- /api/ route
- 192B download size
- 25ms to respond
As the request in server actions points to the route itself it's likely running much more code than the /api route which just returns some JSON.
That said 100% agree this is a much better DX with types flowing through and love to see new and creative approaches to current problems!
My new favorite way of fetching data is with infinite loading through a server action. 10x devs use POST requests to get data.
That's a problem
10x devs use 500 to denote successful request on api endpoint
Mutations are meant to be used for creating or altering data -- i.e to mutate it., not for fetching data. Fetching data should use useQuery. POST, PATCH, PUT requests should use useMutation.
Amazing! Thanks to this video I went from Apprentice Brick Layer to Senior-Seasoned Full-Stackoverflow-BackToFront-End Devengineer and ready for retirement.
😂😂😂
instead of using react-query I would just implement a custom hook for the project that reduce redundancy and track request state.
You can make it typed for typescript easily with a generic function, like
This is great, I’ve been using this.
Once you need to protect the mutations, schema validation or some kind of middleware, I’ve found trpc to be the best option. You can call trpc mutations in server actions.
If you’re not using react query, then next-safe-action is a good choice
I second this trpc api all the way. Schema validation is a pain writing manually and what's more important consistently.
Or just use next-safe-actions
Not sure why you're using a mutation when this looks like a query
Sometimes you want to perform a GET request when a user clicks a button for example. You can't really control when a useQuery runs unless you specify the enabled property
@@outis99 There are ways to do that from query (if i'm not mistaken).
useQuery exports a "refetch" function for that.
We can also invalidate the specific query key using queryClient (useQueryClient).
And there might be other ways.
I might not be right about this, but as far as i know, mutate are intended for post, put, etc.
If anyone has a deeper understanding about react-query, i'm here to learn :D
@@outis99 server actions are always POST requests
@@StabilDEV I guess what he means is that with useQuery the query performs when the component is mounted and if yout want to controll it yout need to pass the enabled property and use refetch but with useMutation you just need to use the mutate function.
@@josepazmino842 yes, but the reason hes using useMutation is not for this reason. Like Stabildev said, all server actions are post so you can't use useQuery.
You can also add a type to the useMutation like useMutation
It seems like the reason this works in the video is because typescript can infer the types from the getUser function you defined. Still a nice pattern! Thanks for sharing!
I scrolled down the comments just to make sure someone mentioned this haha
Yeah but that would mean you have to maintain the types.
@@derkaouiabdelatif1524lol ditto
usemutation for getting data? lol, what about in memory cache?
You can use this approach with useQuery as well 👍
@@TheBelafleck server actions do not run in parallel. They are always sequential, by design. Fetching data like this is a disaster.
server actions are not made for fetching data, for this case better use "server only", (it is not provided by default). Basically you can achieve the same using native fetch and built in loading, suspense, error boundary. The big difference is because you use a hook, you are not more purely on server side, this require directive "use client", but your approach is much cleaner.
Good points. So it's better to not use react--query with server actions, because such action can't be explicitly marked as "server only"
I am still not fond of writing back-end code with Next.js. I simply do not see it becoming manageable as the project grows in size and complexity. It seems to be more suitable for a small-scale project, such blogging, with minimal logic, where using a large-scale framework, such as .NET or Spring Boot, would indeed be an overkill.
Furthermore, I followed the official tutorial from Next.js' website and there they even wrote SQL code, an approach that reminded me of when I started learning how to code with PHP, and I would write SQL, PHP, and HTML all together. It was about 10 years ago or so.
A simple CRUD, tops.
If you can manage it in .NET you can manage it in Next.js. Structuring a project has nothing to do with the language or framework.
Combination of Tanstack/react-query and next js server action would make my life so much easier.
Unlike queries, mutations are typically used to create/update/delete data or perform server side-effects. For this purpose, TanStack Query exports a useMutation hook. That from react-query documentation
Its nice but our component will be client side , not server side and our react query is still big dependency to use in our components
I guess the only "drawback" is that it only works in client components, since it's a hook. But still a pretty great solution, I absolutely love react query!
Is that really a drawback? You can just run fetch directly in a server component
@@redeemr that's why I put it on quotes xD
@@redeemr does this mean you must maintain the same tags on the Tanstack Query side and Server Actions? How does this look in practice, to minimize the need to manage 2 caches?
@@teeldinho471 Pretty sure you have to manage 2 caches
@@teeldinho471 Well, you could just not use Next.js cache, passing "no-store" to your fetchs or using some lib that doesn't depend on fetch like Axios to make requests.
I found setting up TRPC a nightmare with inadequate documentation, so I’ve just been exporting/importing types all this while. But this is actually a killer combo - thank you so much!
same dude!! tRPC is such a nice tool but the setup has been so unintuitive for me too. appreciate ya
It takes like 2 mins or less to setup trpc
Use T3 stack.
Legit been doing this for time, I'm glad this got Josh's cosign ;)
I fucking love you, been stuck with fetching api because of cors or wtf that was and the route method was not working, decided to sleep, after 4 hours and BAM in the morning watched your vid and it worked, ty,
woah thanks Josh for sharing this incredible technique for fetching data way easier than creating api routes, Im already tired of doing bunch of routes lol.
haha:
function useTypeSafeActionState(serverAction: T, initialState: U): [state: ReturnType | U, formAction: something] {
return useActionState(serverAction, initialState)
}
Typesafe now within 3 lines.
Hey Josh, I definitely like this approach but the NEXT team are saying "handle form submissions and data mutations" and i have seen around the internet to not to use for as "GET" use only as Mutation function and so, What are your thoughts on this. Is it really a thing to use only as a Mutation or we can do whatever inside it without worrying about these things?
I’ve tried using actions for getting data. Went back to using usual fetch. Reason?
Server actions are executed sequentially, they can not run in parallel. And any other user interaction will be blocked until action is done. This has a huge impact on performance😕
Also, POST requests don’t really have the caching benefits of GET requests
And there is no caching on server actions
Thanks guys. My doubt is cleared now. But is there any way to get type safety for this use case? (other than trpc)
honestly i dont follow closely what they say, i feel like this approach is awesome and its so productive
❤@@vasyaqwe2087
Tan stack query hooks actually do a pretty good job inferring types, in some special cases you might need to pass generic parameters for type safety, but you can definitely use them without the server action combination.
I think Upstash are lucky to have you in their team.. Amazing tutorial Josh 🎉
Do you typically separate out your server actions into separate files or just include them all in an "actions.ts" file? I'm curious how you prefer to structure your files/folders in general, I'd love to see a video on that at some point!
interested
Also interested. Currently I have my actions in /server/actions with each being grouped somehow if possible. Grouped based on table names or something. But I've seen one file and I've seen a single actions.ts in the same directory as the page using that action
I like the idea, but why would you use a mutation function to get data? Why not use the useQuery hook to get the data in that example? Apart from that the idea is very good!
+1, I use useQuery and pass a server action to it so we get the data on component render and not depend on user actions to fetch data.
@@fitimbytyci345 You're doing it right in this case, but don't forget mutations when the data will be created/updated/deleted with users actions, it's easier to implement optimistic updates with it.
Didn't know react query works with server actions, that's great!
Only downside is, server actions are always POST, which doesn't make much sense. I mean, you can get data on the server, but if you're using react query and want to have any sort of dynamic loading going on, you'll still need GET endpoints for actual queries.
I mean, maybe not *need*, but I refuse to ever fetch data with POST.
I'd honestly stick to the default verbose server actions (maybe wrapped behind a custom hook) if only they stopped using FormData. That api has been growing on me, but I really don't want FormData.
This looks great! However, doesn't react query provide support for typescript using generic types? I personally love extracting every useState and useMutation with fetching logic into separate hook, which take as a parameter the query options object (which also has special type provided by react query), therefore making those hooks highly reusable across many different components due to their customizability.
Nice one. Question: In comparison, how do you feel about the t3-stack, or TRPC in general? Sounds like a very similar approach.
yep its similar... server actions are simply auto-generated api routes, same as trpc. So in my opinion its just a less mature alternative. The only thing server actions have going for them is they are "native to the framework" and hence can do revalidateTag() and notify the client to do the router.refresh() equivalent automatically.
server actions theoretically eliminate the need for TRPC. But TRPC gives you more than just type safe requests.
been using this for a while too
it's pretty cool
fascinating! awesome! thank you very much indeed, Josh
Pairing this with initialData sounds OP. And also exporting the queryOptions from the action itself.
If by query options you mean the data, loading and error states, it won’t work in app router as actions are to be defined on server and hooks on the client
I am old school developer. I just put Mvc everywhere it works everywhere. For everything.
Hmm why tanstack query isn't typesafe (btw why use useMutation for plain fetching?) ?
You can specify types for response where you set up your API handlers/
query functions (and by sharing type declaration across front and beckend you can get typesafety if you wnat/need across both project even if they are separate)
I think it's meant to be a post request but getUser is a bad example for that.
Also like you said, you could just specify the data type returned by the fetch request as a typescript interface, so this seems like he's demonstrating a benefit that isn't actually a benefit unless he's assuming we are working with JavaScript and not TypeSrcipt I guess
I don’t know. With my implementations I make my mutations typesafe without server action. Just react query
But then you have to create your own types when the code is already giving you the types. This method gets the types from the code/libraries. However the downside of this method, like you mentioned, is it uses only post requests(server actions are only post req) which don't cache. If you want 'type safety' either use trpc, server components, or validate with zod. This is mostly a dx issue anyways, your method works fine if done properly.
What do you think about react-query in combination with hono? Maybe not so simple like server actions but much more cleaner and also type-safe.
If you want to know the type when using useQuery or useMutation, you can just define the type on that like useQuery() then data must be Response | undefined type
so you dont need to use server action on that.
While not sure about react query, RTK query does give the ability to add types for both response types and query args with all the isLoading, error, etc states
Yes, React Query also has that ability, but inference is just better
What about error handling with useMutation? Server actions only returns plain objects. You did not mention that?
you can throw errors on your own
@@anhai-d9z yeah I know I wrote a simple actionWrapper function that throws for mutation, but I just wonder how other people do that 😃
is great for accomplished your API code with your Presentation code - like a junior dev
The best data fetching method in Nextjs! Thanks!
Would you still use Mutation if the data needs to be loaded on the pageLoad? As per my understanding, mutations are generally used for CRUD operation with server and not really for data fetching.
We've been using this pattern without server actions for a long time. I can share our project structure if you're interested
Wow! I think this has the potential to eliminate the need for tRPC. That means zero configuration for Front and Back type-safety, and less bloated full-stack projects. It's amazing to say the least! 🔥
create a josh stack please, a community driven open-source
This approach is not good, because POST requests will not get cached by react-query, nextjs or anything. It's just a new request everytime
I mean that's by design, POST request shouldn't be used to GET a resource which I would expect to be cached
Edit: saw the other comments and understood what you meant, yep bad approach
You can wrap ReactQuery hooks inside of your own custom hooks, then you can get type safety and any additional business logic, or statuses you need before returning to the page components. I will keeping using this pattern + api routes for now, still not seeing benefits from server actions, and it is a lot less intuitive to use.
Amazing! Is possible to protect the server action with authentication? For eg. Create task action cannot be used before you logged in
Yes of course. You have access to cookie in server, and you can get token and check it in server. But I use nextauth
This deserves a like ! I think you can use "use server" instead of functions, it would be nice if you can just export a custom hooks that can be re-used without thinking about importing different dependencies (similar to trpc)
Does this help with "protecting" an api key, so the user cannot just simply take it out of the network tab? If not, do you have any recommendations on how to implement client side actions like updating, deleting, etc. without exposing the token to the client?
I have a problem, if you want to handle errors, in Server action directly throw errors in development mode can, But in production mode the error message will be hidden, how to solve?
Same issue, did you find a solution ?
The problem is, that it‘s always a post-request. Isn‘t it better to use Hono/ElysiaJS in the API-route like you did in another video? I am trying ElysiaJS at the moment and the „eden treaty“ is amazing. You can use it in react-query and in react server components. This way you can use middleware and all other stuff, you are used to on api-servers. And it‘s easy to seperate them if needed.
what benefit does "use server" directive have in getUser function? what if instead of making it a server action we made it a normal function without "use server" directive?
What about server components, query inside metadata, HydrationBoundary and prefetch query, cache concerns between next/fetch and RQ? would be great if you could cover all fetching aspects :) All the best
@Josh, have you tried this with Prisma. Prisma doesn't allow fetching on client, and if you mark action as 'use server' then type safety is gone.
This is really cool Josh! Thanks for sharing ;).
Title should be changed to "Mutating Data Doesn't Get Better Than This"
Basic react query with Redux. There is such a close connection in syntax.
I was the doing the same, its really a good pattern for fetching data.
I like the server prefix.
Congratulations, you just reinvented tRPC
Do you think it's a good idea to call an external API from from the server action?
what you are talking about is native with Nuxt, data fetching, fully typesafe
amazing, react-query
SWR > react-query 😊
it seems very simple compared to tRPC but are there any disadvantages
If you don't need caching or invalidation you can even invoke the server action within a custom handler without using RTK mutations, but you have to set a custom loading state, which kinda sucks tho. Also there's some weird errors that occur on the form html element when using server actions directly on them, which is really annoying. So yeah. Invoking actions inside handlers/useEffect or simply react query is much more preferable.
Wow pretty soon next.js will be able to do things I could do 15 years ago in asp web forms amazing.
Nuxt 3 has it all built-in, way less complex great typesafe DX
BuT ReAcT more jobs !!!
Is the actions.js file a good place to have functions that call APIs?
I think that server actions are called sequentially and not in parallel by Next (since that is considered to be most appropriate for mutations). So, this pattern might introduce really bad client-server waterfalls and lead to poor performance.
This is excellent if you have project which is browser only, but if project get bigger, and mobile app is needed i think server actions might be problematic. Please correct me if im wrong.
For me there’s no reason to use such a big library like react-query just for data fetching, it has a lot more but for a simple fetch just use standard library. Dont overengineer and add a lot of complex to a simple fetch.
btw, you could create your own hook (which you’ll write once and use it a Million times) and it may be more performant
What if you didn’t use use server directive in actions file that would still be the same no?
Anyone? What if getUser isnot a server action and is just normal function?
Your energy is top-notch 😅😅
looks great and similar to the idea used in t3-app actually.
It is suppose nodejs and js(frontend backend) work similarly then when both move to typescript safe type, it should too. but new framework dont copy old stuff that good. This kind of pattern already exist from 10 year ago from knockoutjs , emberjs etc.
Because fullstack developer trend, we love js too much, we have good workflow. now in react, too much noise, and ppl dont care good small pattern.
What is the benefit of using server actions for fetching instead of TRPC?
i don't see any also
Good question
@@FIash911 how you deal with optimistic updates using trpc? Nowadays we have it built in in react, but I does't work well if trpc.
so what about a server componet for fetching data ? same approach ?
i am think i am only using like combination of tankstack and servertion but no. Now i am confident bro thanks
is this working if we disable JS?
i thought the benefit of server actions is to be able still to mutate even if user does not run JS
Dislike the naming conventions, mutate != GET requests. The destructuring renaming adds mental overload for no reason. Using API routes is still OG in enterprise level apps imo
can i have someone opinion on my approach?
like im using server actions for fetching data and in pages.tsx is server component which i use the server actions function, and im passing the data trough props to specific component inside page.tsx which all the components here is client side component. then rendering the data in this client side.
is this a good approach?
and with react-query could it run on server components?
Yes I do kinda the same. In page.tsx which is async I make a fetch request to retrieve data from db and then pass this data as props to a client component. For the second question I can't answer you because I use nextjs server actions and I'm happy with it for now.
This approach makes sense with mutations, but how would this work with fetching a query?
afaik 'data' in useMutation works differently, it is "the last successfully resolved data for the mutation", and since it doesn't make sense to call 'mutate' on a query, how do you get the data?
I would love to have a similar approach for simple GETs, that doesn't involve using server components and giving up on react-query and its loading state management
It works the same, with useQuery you pass a server action to the queryFn, the query will be called automatically when the component renders just like any query.
I like this approach but I have a feeling the default method of a server action being POST can cause issues somewhere.
Mind blowing 🤯 I can't believe josh how you you teaching and also how you making awesome videos such like this video awesome ❤
This is very handy BUT it comes with a very big catch: you can't abort server actions 🥶
And every issue/discussion about adding a way to cancel server action in the Next community has been ignored so far from what I have seen.
Idk I used this all the time so far but I am starting to think that this should be classified as an anti-pattern, we should use "actions" for real actions, not to fetch data.
From my experience tRPC is still the way to go and using server actions for fetching data with type-safety and without surprises along the way.
Why useMutation instead of useQuery if you're just... querying for data?
Pls someone tell me the right way to fetch data in server components. I currently fetch directly from my db on the server side but I noticed there’s no caching.
all this is nice, but we just not using useMutation as it is supposed to be used. (we have to mutate with useMutation)
why just dont pass server action (that in your case gets data) to queryFn?
const query = useQuery({ queryKey: ['todos'], queryFn: __your_server_action_getting_data__ })
and one more thing, even though it works server actions are idiomaticaly used basicaly like a post request (mutate data) - from documentation (not to get data)
god knows if it is ok use it in production for now
I basically do this but with TRPC actions because I like to make all my DB calls from a router still 😊
the desktop wallpaper
windows x shrek collab
well, it looks ok, but what about doing like POST or PUT. Is there a generic solution for all types of requests?
How would you use this pattern for external APIs?
could it possibly replace the trpc as a whole? this combination of server actions and react query?
Possible. Especially if used in combination with cookies for authentication so you can fetch the current session anywhere on the server. But also im realizing that server actions are executing sequentially and not in parallel. What do you think?
Who said that you can know the type returned by react query? you can pass a generic argument and it will use that as the fetched resource type on the data prop.
Well and very well explained, thanks so much
Does it have any effect on caching responses?
This is useful for me! Thanks Josh
use zod for validation and type safety?
thank you josh , but i have another opinion
i think no i will not use it , by this you are fetching data in client side , but in next the standard is fetching data in server components , the data fetching should be in the server , maybe we can find some good usecase but in general fetching data in server + skeleton components in loading file will be better in my opinion !