Client/Server Mutations
Hey, I'm trying to wrap my head around client vs server components in my app. Here's the basic structure I'm using:
This approach works well for returning the data in a clean and fast way while allowing for interactivity in the form. Where I'm getting lost is how to submit the form. I can submit it client side with the
useMutate
hook, but then I'm not sure how to fetch new data.
It seems more ideal to use the server mutate
function instead, but I can't figure out how to call that from a client component.
I can make this all work with client components, but it seems like the direction of the App router in Next.js is to move toward server components.
Thanks4 Replies
You can look into server actions
Data Fetching: Server Actions and Mutations | Next.js
Learn how to handle form submissions and data mutations with Next.js.
Great, thanks for the direction. Definitely wrapping my head around the server-oriented direction still and trying to understand the patterns. Thanks
Ok, spent a few hours on this and here's what I ended up with:
The way T3 is setup using the Next.js App Router, it seems like my api router is already using server actions, but maybe I'm misunderstanding.
OnSave, I'm able to call the api router with
mutation.mutateAsync(values);
My Next challenge was how do I take those returned values and repopulate the form? The issue being if there are any differences between what was saved vs the state of the form. This one took me a while because I'm using uncontrolled form field. What seems to work is to use the React Hook Forms reset
method to replace the default values.
Anyway, I don't know if there's a better way, but it seems to be working."The issue being if there are any differences between what was saved vs the state of the form"
I would return the new
state
and save it inside the initialState
(which is passed onto the server action). And based on that the form could update reflecting changes like success or fail, etc
But your method works (if it works, it works, dont change it)
this is just how i might complete the task