React Hook Form & React 19 Form Actions, The Right Way

Поделиться
HTML-код
  • Опубликовано: 9 янв 2025

Комментарии • 280

  • @scottsmith416
    @scottsmith416 9 месяцев назад +5

    About to launch my first freelance production application and this video came at the right time! Used this library at my previous job all the time, but configuring it with server actions was a bit tricky and new to me. Thanks again, Jack! This combined with your "lightning fast" React Context state manager is a power horse setup!

  • @mashermack
    @mashermack 6 месяцев назад +11

    I wish nextjs documentation would be this clear instead of half-explained stuff. Amazing stuff, literally all 16 minutes covered all my issues with server actions and hook form.

  • @dmitrypalamarchuk3501
    @dmitrypalamarchuk3501 4 дня назад

    finaly I found real world example with clear explanation, thank you so much. I like that you verify the hypotesa about correct way of solving the problem step by step, with check on both sides server and client. Great work!

  • @dwolrdcojp
    @dwolrdcojp 10 месяцев назад +14

    This is exactly how we’ve been doing it in our next.js app router production application. Yes a lot of boiler plate but you get validation at client and the server and status messages sent back from the server to the user. I believe RHF is working on integrating with server actions / react server components which will reduce boilerplate and improve the api for doing all this.

    • @Divineleo2023
      @Divineleo2023 10 месяцев назад

      I am also using shadcn so and the above video shown way of doing for both of my projects

  • @LucasGabriel-xz8nk
    @LucasGabriel-xz8nk 8 месяцев назад +12

    Dude I owe you my life, this was the ONLY place I could find the solutions I needed. Thank you so much

  • @PeterJaffray
    @PeterJaffray 8 месяцев назад +15

    Holy shit Jack. Every time I am working my project - I see your videos pop up with exactly the right topic. It's like you are spying on me. You are the best teacher I ever had.

  • @clockworkop
    @clockworkop 10 месяцев назад +37

    And we are back to 200 response with an error inside

  • @dazecm
    @dazecm 10 месяцев назад

    Every time I encounter one of your videos in my RUclips feed I become a little better at web tech. Thanks for just being there like a tiny jewel amidst all the junk that often pollutes my RUclips feed. 🙂

  • @santiagogaleano5884
    @santiagogaleano5884 5 месяцев назад +1

    Excellent tutorial, thanks for paying attention to every detail Jack!

  • @MarosiMate-sq2wm
    @MarosiMate-sq2wm 3 месяца назад +1

    Was struggling with this for quite a bit. This helped me solves the problems.

  • @helleye311
    @helleye311 10 месяцев назад +12

    A bit verbose but pretty cool! I'd definitely write some wrappers for handling all the zod stuff and mapping between formdata and objects, 100 line component for just an email form is a bit much.
    That's also why I don't like this component pattern with , I usually wrap this with a single component as well. It's great when a library uses it because you can wrap it however you please, but building inputs with more than one component gets tiring pretty fast.

  • @JoseHenrique-xg1lp
    @JoseHenrique-xg1lp 2 месяца назад

    I like how excited he is. Totally worth watching

  • @BusinessAutomatedTutorials
    @BusinessAutomatedTutorials 3 дня назад +1

    This was an excellent explanation. thank you for that. I still prefer to use Front end validation first instead of relying on server validation only. Combining Hook forms and action took me a while..

  • @victorlongon
    @victorlongon 10 месяцев назад +1

    I was fiddling with this for a while, didnt quite get with having the client and server validation. Great to know how to do it know! ❤

  • @DewinderB
    @DewinderB Месяц назад +5

    sorry this is not working with React 19 and Nextjs:
    An async function was passed to useActionState, but it was dispatched outside of an action context. This is likely not what you intended. Either pass the dispatch function to an `action` prop, or dispatch manually inside `startTransition`
    const [state, formAction] = useActionState(onSubmitAction, {message: ''}); is sending this faillure.

  • @iamvoid
    @iamvoid 8 месяцев назад +8

    If anyone gets this error "A React form was unexpectedly submitted. If you called form.submit() manually, consider using form.requestSubmit() instead," here's a fix. Rather than using a reference to submit the form, you can actually use the formAction (2nd array element when instantiating useFormState) as function to pass the submission data directly to the server action. You'll need to adjust your onSubmit function to accept data as its first and only param. This will still only execute once the validation is satisfied. Then, you can execute formAction(data). If you're iterating over your form entries in your server action since it was previously expecting FormData, you won't need to anymore. You'll actually get an error if you still do. Also, with this method you don't actually need the action prop on the form either since you're calling it yourself.

    • @Mostuffa_
      @Mostuffa_ 8 месяцев назад +3

      but does it make it still a "server actions" ? or just a function running on the server ? and is it still going to work while JS is disables on the browser ?
      I guess that client validation isn't yet supported cause I scanned every github issue and Stackoverflow question to no avail :')

    • @iamtlessd
      @iamtlessd 7 месяцев назад +2

      Two things.
      Removing the action from kills the no javascript form.
      If you use event.preventDefault, or just form.handleSubmit, it kills useFormStatus that just doesn't work no more.

    • @EddieBlundell
      @EddieBlundell 7 месяцев назад +1

      Spent hours fighting this- initial render is fine, then subsequent client renders is where the issue happens. Seems we can't have both no-js form + js validation just yet.

    • @iamvoid
      @iamvoid 7 месяцев назад

      @@iamtlessd I did end up adding it back in.

    • @ericmathison
      @ericmathison 2 месяца назад

      For anyone running into this issue, please take a look at Jack's updated code in the repo. You need to change the onSubmit handler to the following:
      onSubmit={(event) => {
      event.preventDefault()
      form.handleSubmit(() => formAction(new FormData(formRef.current!)))(
      event
      )
      }}

  • @phantom7132
    @phantom7132 6 месяцев назад +1

    Much love for your high-quality content! Always learnings new things 🙂

  • @goatslayer5957
    @goatslayer5957 10 месяцев назад +2

    Loving the website you built btw Jack!!! Great timing

  • @gurditt_singh
    @gurditt_singh 5 месяцев назад +1

    i was so confused by this on my own, thank you!

  • @Skillthrive
    @Skillthrive 9 месяцев назад +16

    I get the following error:
    Error: A React form was unexpectedly submitted. If you called form.submit() manually, consider using form.requestSubmit() instead. If you're trying to use event.stopPropagation() in a submit event handler, consider also calling event.preventDefault().

    • @benbrkic
      @benbrkic 8 месяцев назад +1

      same here :(

    • @Aralf
      @Aralf 7 месяцев назад +1

      Same 🥲

    • @MagdalenaPizarroOrtega
      @MagdalenaPizarroOrtega 7 месяцев назад

      i just refreshed the site and it went away 😶

    • @imrandev20
      @imrandev20 6 месяцев назад +3

      @@MagdalenaPizarroOrtega It comes back once you submit the form again. Also, the action doesn't seem to be working.

    • @whitefluffycloud
      @whitefluffycloud 6 месяцев назад

      I can't post the link, but the comment on this path on Github helped me solve it: /vercel/next.js/discussions/56234#discussioncomment-9861897

  • @hovhadovah
    @hovhadovah 7 месяцев назад +2

    I really wish there were a better way to do all this, as it's quite a lot of boilerplate. Especially the part where you need to re-stringify the FormData to pass down the fields from the server if zod validation fails. For example, what if a field is of a numeric or boolean or some other type? Ideally you shouldn't have to convert those types yourself. You already have a zod schema, so it would be nice to reuse it.
    I've been tinkering with Svelte's superforms library and it's phenomenal. It gives you all of this for free, and it works with and without JS. Plus you get inline errors and auto-populated field data from the server. The only downside is that it only supports method="POST".

  • @flavioneto1081
    @flavioneto1081 8 месяцев назад +11

    hey Jack! Great video! I followed your fix for the "React form was unexpectedly submitted" case, but now as I tried to add the useFormStatus hook, it doesn't get aware of the pending state, because we are basically making our way around the "action" prop itself. Do you have an idea to solve this? Thanks!

    • @flavioneto1081
      @flavioneto1081 8 месяцев назад +4

      ok sharing my workaround for this: i moved the client side validation to happen while the user fills the form, so it is not necessary for us to call the form.handleSubmit, and this frees the action behavior.
      steps: i deleted the "onSubmit" thing from the form and left only the action. then i changed useForm config to contain "mode: 'all'", for it to validate the form not only on submit, but also on blur and on change. and lastly i added "disabled={!form.formState.isValid}" to my submit button

    • @imrandev20
      @imrandev20 6 месяцев назад

      @@flavioneto1081 Thanks, this helped a lot.

    • @imrandev20
      @imrandev20 6 месяцев назад

      onSubmit={(e) => {
      e.preventDefault();
      return form.handleSubmit(() => {
      formAction(new FormData(formRef.current!));
      })(e);
      }}
      Try this instead if you haven't found a solution already. It might help future visitors as well.

    • @tombaaaaa
      @tombaaaaa 4 месяца назад

      @@flavioneto1081 thank you! this worked for me

    • @nickwoodward819
      @nickwoodward819 2 месяца назад

      Did he mention the fix in this video, or elsewhere? don't remember him mentioning it?

  • @iamprincemuel
    @iamprincemuel 10 месяцев назад +1

    Man, this is awesome 💯 This is one of the reasons I ditched react hook form due to the fact I thought I'd be loosing the benefit of server-side validation. Goes to show you that Knowledge is Power. Thanks for this, and I'm checking out your site ASAP 😍

  • @JGBSolutions
    @JGBSolutions 10 месяцев назад +2

    Nice tutorial! react-hook-form offers APIs like setError to manually set the error message if you wanted to target the field with the error and put your message there too.

  • @albert21994
    @albert21994 10 месяцев назад +1

    insanely good and informative! thank you!

  • @lev1ato
    @lev1ato 8 месяцев назад

    Amazing guide, and thank you for the free tutorials!

  • @zaheerabbas8344
    @zaheerabbas8344 10 месяцев назад +1

    detailed description of the nextjs form.thanks,♥

  • @guitox155
    @guitox155 7 месяцев назад

    Much appreciated, I have spent the whole day trying to do that before watching your video. lol

  • @gavinlindridge
    @gavinlindridge 10 месяцев назад +2

    This form pattern with fromEntries works nice with flat objects but how would we handle more complex form shapes.
    Really great content 👍

  • @codernerd7076
    @codernerd7076 10 месяцев назад +3

    Next.js is the best thanks for the video and the free forum course!!!

  • @nickwoodward819
    @nickwoodward819 6 месяцев назад

    sorry jack, another question if you don't mind!
    @10:55, why does calling formRef.current.submit() now prevent the action from submitting (say when validation fails) when it didn't when JS was disabled?

    • @nickwoodward819
      @nickwoodward819 6 месяцев назад

      ah, the second callback to handleSubmit is the error function, which does nothing

    • @jherr
      @jherr  6 месяцев назад

      Please check the most recent code on github. It should work for you.

    • @User2-r1p
      @User2-r1p 6 месяцев назад

      @@jherr can you please suggest, how we can manage the loading/isSubmitting state of the form in your example. (disable the submit button)

  • @nickwoodward819
    @nickwoodward819 6 месяцев назад +1

    not sure if it's easy or not to add a note to a video, but @13:04 needs JS disabled. confused me for a sec :)

  • @GabrielMartinez-ez9ue
    @GabrielMartinez-ez9ue Месяц назад +1

    is there a reason react-hook-form or even shadcn which uses it does not recommend this approach?

  • @kH-ul4hk
    @kH-ul4hk 10 месяцев назад +2

    This is amazing! How would you make it for multi-step/wizard forms, so that it works with actions? Normally you make it separate forms and store it in a (global) state, so how would this work for actions?

    • @jherr
      @jherr  10 месяцев назад +1

      I might consider using XState for that.

    • @cwirus99
      @cwirus99 10 месяцев назад

      Why wouldn't you just wrap all your steps/slides in a form element?

    • @jherr
      @jherr  10 месяцев назад

      @@cwirus99 Did I say I wouldn't do that? How is that incompatible with XState?

    • @kH-ul4hk
      @kH-ul4hk 10 месяцев назад

      wouldn't work easily with the client side validation for each step. The validation would trigger for the whole form at the end or for the whole form at each step@@cwirus99

    • @cwirus99
      @cwirus99 10 месяцев назад

      @@jherr No no, I was answering the guy above. Nothing wrong with your answer ;)

  • @mrlectus
    @mrlectus 3 месяца назад +1

    This Guy is The MAN

  • @kyrregjerstad
    @kyrregjerstad 9 месяцев назад +1

    Any suggestions how to disable the submit button while the form is submitting? The RHF form.formState.isSubmitting is not working with server actions

  • @joshuagalit6936
    @joshuagalit6936 6 месяцев назад +1

    This is amazing!!

  • @frialdhyketty7950
    @frialdhyketty7950 8 месяцев назад +1

    awesome, but how do we show loading indicator when submit, any suggestion ?

  • @alexandremondaini
    @alexandremondaini 4 месяца назад +1

    this is only working for me with textarea and input fields from shadn-ui , things like the implementation of combobox form do not work somehow , don't know why

    • @alexandertarasenko3038
      @alexandertarasenko3038 3 месяца назад

      could be because combobx field has no name and for form data it need input name - otherwise it won't be in form data.

    • @alexandremondaini
      @alexandremondaini 3 месяца назад

      @@alexandertarasenko3038 shacn-ui has a form version of combobox. I used that...

  • @cesarquispe2413
    @cesarquispe2413 7 месяцев назад

    Cool video Jack! I'm right now dealing with some forms in apps I'm currently working. Just a quick question: since Server Actions are handling the 'POST' request we are sending to the server, what's the purpose of adding the attribute `onSubmit` in the element? Isn't the attribute `action` handling the form submission? Looks like all the client side validation is being made with no problem even without the `onSubmit` attribute, from what I've tested. Thanks again!

  • @RapidD
    @RapidD 2 месяца назад

    In the formSubmit.ts what is the purpose of looping the formData again to fields const after parse failure? Could you not just use the formData directly for the return, since it's just the same? Or am I missing something here?

  • @good-dev-student
    @good-dev-student 9 месяцев назад +2

    Video montage is awesome

  • @gamingwolf3385
    @gamingwolf3385 8 месяцев назад

    Great video , i learnt a lot of new tricks thank you , but i have one remark , you can give the server actions data returned from validation directly without transform it to formData 😅

  • @puyaars638
    @puyaars638 10 месяцев назад +1

    one thing I find useful is that you dont nessasarily have to use formdata , you could pass any parsable object to server action

    • @ivodelev9794
      @ivodelev9794 10 месяцев назад

      true, but how can you send File types or Date objects.

  • @kevinpruett
    @kevinpruett 10 месяцев назад

    Great video! Where would you execute client side optimistic updates with `useOptimistic`?

  • @elldy001
    @elldy001 10 месяцев назад +2

    Great video, but I have run into a weird problem that some other people have also mentioned here. Submit (randomly) don't work and error: "Uncaught Error: A React form was unexpectedly submitted. If you called form.submit() manually, consider using form.requestSubmit() instead. If you're trying to use event.stopPropagation() in a submit event handler, consider also calling event.preventDefault()." is displayed. Not sure what could be the cause.

    • @jherr
      @jherr  10 месяцев назад +1

      I've added some code to the onSubmit in the repo. Have a look and see how that works for yah.

    • @Aleksey-n5h
      @Aleksey-n5h 10 месяцев назад

      @@jherr It still causes the same error with parallel and intercepting routing

    • @jherr
      @jherr  10 месяцев назад +2

      If you are getting that error try this instead:
      onSubmit={(e) => {
      e.preventDefault();
      return form.handleSubmit(() => {
      action(new FormData(formRef.current!));
      })(e);
      }}

    • @firstian
      @firstian 8 месяцев назад

      @@jherr That works, sort of, as in the error no longer shows up. However, because this new version is calling the action from onSubmit, useFormStatus is no longer giving the pending status.

    • @imrandev20
      @imrandev20 6 месяцев назад

      @@jherr Thanks. It helped me.

  • @vicli5732
    @vicli5732 7 месяцев назад +1

    Good idea. But got an error "An async function was passed to useActionState, but it was dispatched outside of an action context. This is likely not what you intended. Either pass the dispatch function to an `action` prop, or dispatch manually inside `startTransition`"

    • @vicli5732
      @vicli5732 7 месяцев назад

      I made it working.
      //Form Validation
      const { register, handleSubmit, reset, formState: { errors } } = useForm({}); //useForm();
      const formRef = useRef(null);
      const [pending, startTransition] = useTransition();
      const onSubmit: SubmitHandler = (data) => {alert('in onSubmit');console.log(data);
      //submitAction(new FormData(formRef.current!));
      startTransition(async () => { alert('in startTransition'); await submitAction(new FormData(formRef.current!));})
      };

    • @alexandremondaini
      @alexandremondaini 4 месяца назад

      refresh page

    • @lucnguyenngoc5085
      @lucnguyenngoc5085 27 дней назад

      you has solution yet ? please help me

  • @nickwoodward819
    @nickwoodward819 5 месяцев назад

    Hi Jack. Any ideas why I might have problems redirecting back to a login form using this approach?
    I get an unhandled runtime exception that doesn't occur if the page is manually navigated to or refreshed :/
    > Error: A React form was unexpectedly submitted. If you called form.submit() manually, consider using form.requestSubmit() instead. If you're trying to use event.stopPropagation() in a submit event handler, consider also calling event.preventDefault().

  • @adamovicslobodan3331
    @adamovicslobodan3331 3 месяца назад

    Hey Jack. Nice content man! Helped me a lot.
    I have also a question though:
    When I have a loading.tsx in the root or even a Suspense component wrapper around the form I am using, when I disabled JS, app is stuck on Loading or Suspense component content. Do you know how to fix that issue?

  • @TheStallion1319
    @TheStallion1319 Месяц назад +3

    tbh i think we might have overcomplicated forms

  • @alexandremondaini
    @alexandremondaini 4 месяца назад

    i followed this but i am using different components of shadcn like combobox form and text area, only text area works with directive

  • @sebap_xc
    @sebap_xc 8 месяцев назад

    Following you great tutorial, It reloads my page when I submit the form when I add onSubmit beside action. Do you know why?

  • @Michael-Martell
    @Michael-Martell Месяц назад

    I got nearly everything completed and working but the form values are one step behind... ie: the parsed.success requires being clicked twice with valid inputs. The first time always comes back as parsed.error. Also, I'm getting a weird error: "An async function was passed to useActionState, but it was dispatched outside of an action context. This is likely not what you intended. Either pass the dispatch function to an `action` prop, or dispatch manually inside `startTransition`" Anybody know how I can fix this?

  • @kaungthantkyaw122
    @kaungthantkyaw122 26 дней назад

    @jherr, which theme is that.

  • @codeyalaya
    @codeyalaya 9 месяцев назад +1

    your code does not work when deployed to vercel and javascript disabled

  • @randomforest_dev
    @randomforest_dev 10 месяцев назад

    thanks for this awesome video! I am a bit confused about Form component from shadcn and native form tag. Do we still need to add a form tag inside Form component and if yes, why do we need to pass form object to it as it is just for UI?

    • @ivodelev9794
      @ivodelev9794 10 месяцев назад

      It’s used to pass context to their form components to help abstract some boilerplate is my guess, at least that’s how I would use it

  • @webdev03
    @webdev03 9 месяцев назад +1

    Hello everyone, I have a problem that when I submit using useRef, the page keeps refreshing(11:20 minute). How can I solve this problem?

    • @sebap_xc
      @sebap_xc 8 месяцев назад

      Same. Did you find a solution?

  • @TheGusMP
    @TheGusMP 8 месяцев назад +1

    Good video, but for somereason I've been getting error of "A React form was unexpectedly submitted." with this approach.

    • @jherr
      @jherr  8 месяцев назад +1

      Check out the updates source code in the repo.

  • @IanJamieson
    @IanJamieson 10 месяцев назад

    A nice little withForm HOC would do nicely here.

  • @DanielSpindler-gc7xh
    @DanielSpindler-gc7xh 4 месяца назад

    thats was a nice tutorial, sadly what i came here for wasnt in it XD what about displaying FieldErrors at the fields just like the client side validation? guess i have to interact with the FormMessage somehow?

    • @adamovicslobodan3331
      @adamovicslobodan3331 2 месяца назад

      That is what bothers me right now....I am trying to use setErrors from react-hook-form, inside useEffect hook.

  • @KamalSingh-zo1ol
    @KamalSingh-zo1ol 8 месяцев назад

    Question: How is the form resetting? I even downloaded the github code and ran on local machine. It does not reset form after successful submission. And how do i use function like form.reset()? Also 'status' only shows previous state if rendered outside of form. There are some issues with this approach,.

  • @swrh
    @swrh 10 месяцев назад +2

    Why would I want to handle a form when JavaScript is disabled IN A REACT APP???

    • @Michael-Martell
      @Michael-Martell Месяц назад

      To prevent a malicious user from bypassing your zod validation schema that runs on JS. Also, not losing data is a good thing too.

  • @stancobridge
    @stancobridge 10 месяцев назад

    Will server action capture custom values that is passed to react hook from without form component, for example using setValue from the useForm

    • @jherr
      @jherr  10 месяцев назад

      You get the previous state you can leverage. And you can also add hidden values fto the form.

    • @stancobridge
      @stancobridge 10 месяцев назад

      @jherr Normally, I get the previous state, when the form is submitted and I don't call reset from useForm, the form state remains unchanged, the need for access to the old values is because the server action removes the Value when the browser refreshes.
      Secondly, I don't need to use hidden inputs to set values after building a component that handles this for me and I can just call setValie to do the rest. Say I have a component that holds crops image and send the value of the cropped image to hook from just calling setValue, why will I need this.
      RSC is great, React 19 is cool, but trying to use it to replace everything, creating problems that shouldn't exist in the first place or taking us back to the period where we needed something like react to escape all these is not cool, am yet to understand what it solves.
      Can't I just send the values from useForm to the backend without these extra codes

    • @jherr
      @jherr  10 месяцев назад

      @@stancobridge You can if you don't want to deal with Javascript being disabled.

  • @Tommy-ev6gv
    @Tommy-ev6gv 10 месяцев назад

    What are your thoughts on controlled vs. uncontrolled components? RHF primarily focuses on uncontrolled components. However, in the example you've provided, it's instead a controlled component. Is the trade off worth it?

    • @jherr
      @jherr  10 месяцев назад

      As long as the value is set during the handleSubmit callback I'm good either way. The only specific reason I could see going with controlled is if there were dependent fields, like fields that enable/disable based on other fields.

    • @Tommy-ev6gv
      @Tommy-ev6gv 10 месяцев назад

      ​@@jherr If i'm not mistaken in your video we assign each input field to a state, making it a controlled. So every key stroke in a field causes a re-render. So the performance gains for using RHF is then lost?

    • @jherr
      @jherr  10 месяцев назад +1

      ​@@Tommy-ev6gv I'm not sure that these inputs are controlled. I'm destructuring {...field} into the inputs, and that could just be managing refs. The example is just following the boilerplate code for form inputs provided by shadcn in their react-hook-form integration section. That wasn't the primary point of the example or the video, which is primarily concerned with keeping the client-side validation functionality of RHF while still leveraging `useFormState`.
      I'm also not particularly worried about the performance impact in this case because re-renders in React are expected and in this case would not result in DOM updates even if the inputs were controlled. React leverages a VDOM to ensure that the DOM is never unnecessarily updated. Renders don't updated the DOM directly. Renders create VDOM nodes which are diffed against other VDOM nodes and the DOM is only updated when there is a delta between the old and new tree.

    • @Tommy-ev6gv
      @Tommy-ev6gv 10 месяцев назад

      @@jherr Thanks for the quick replies. I tried the shadcn example and I remembered it complaining about the input fields going from uncontrolled to controlled if you don't provided any default values as you do @2:38.

  • @spickyoo
    @spickyoo 9 месяцев назад +1

    Something about re-creating the formData object (by doing formData.append() a bunch of times) doesn't feel right to me....is there really no way around this? No way to pass something other than FormData to a server action?

    • @jherr
      @jherr  9 месяцев назад +1

      Server actions can take any data format you want (except stuff like functions obviously). The reason we are using formdata here is to pick up the native form behavior that works without JavaScript.

    • @spickyoo
      @spickyoo 9 месяцев назад

      @@jherr Thank you! One thing I still have trouble understanding after watching this (great) video and going through ProNextJs is how file uploads work in this exact stack (react-hook-forms, Zod, shadcn, server actions). Seems like files must be wrapped inside FormData but I could be wrong because I can't get it to work :)

  • @Gダビッド
    @Gダビッド 9 месяцев назад

    I need your help, Idk why it doesn't work in a vercel deployment

  • @xtromp
    @xtromp 10 месяцев назад +1

    If I disable client side validation, as long as there are validation error, when I submit the form, the page doesn't refresh. But once server side validation passes, the page reloads on submit. Do you also have this issue? Otherwise, great video !

    • @sebap_xc
      @sebap_xc 8 месяцев назад

      Same. Did you find a solution?

  • @amraromoro
    @amraromoro 10 месяцев назад

    Hi @Jack i tried this and worked by how would we prevent the refresh after submission of the form?

    • @jherr
      @jherr  10 месяцев назад

      With JavaScript disabled? There is no way to prevent the refresh. That's how web forms work. With JavaScript on then you aren't getting a "refresh".

  • @Technology_Forum
    @Technology_Forum 10 месяцев назад

    Also can tell about the terminal settings

  • @codeyalaya
    @codeyalaya 9 месяцев назад

    how to show #contact section of a long page, after submitting form with js disabled. #contact section is at last of the page.

  • @farooqbroberg9349
    @farooqbroberg9349 Месяц назад

    Does this work with MUI instead of shadcn?

  • @JelteHomminga
    @JelteHomminga 8 месяцев назад +1

    great content, but unfortunately the solution is not working for me
    "Uncaught Error: A React form was unexpectedly submitted. If you called form.submit() manually, consider using form.requestSubmit() instead...."
    but unfortunately requestSubmit is not working at all

    • @jherr
      @jherr  8 месяцев назад +2

      Check out the updated code in the repo.

    • @JelteHomminga
      @JelteHomminga 8 месяцев назад

      @@jherr can you explain why would you do this? If we call already the formAction in the onSubmit then what is the benefit of also adding the formAction to the action attribute and the extra complexity with the ref and preventDefault ?
      this seem to be enough for me:

    • @jherr
      @jherr  8 месяцев назад +1

      That will work fine with JavaScript enabled. It won’t work if JavaScript is disabled. If all you need is JavaScript enabled support then that works just fine.

    • @JelteHomminga
      @JelteHomminga 8 месяцев назад

      ​@@jherr thanks for the quick reply, but still trying to understand the benefit of the ref.
      Could you also do
      if it should also work with JavaScript disabled ?

    • @jherr
      @jherr  8 месяцев назад

      @@JelteHomminga I'm sorry, I don't understand the question in the last sentence. onSubmit does not work with JavaScript disabled.

  • @heyFahad
    @heyFahad 4 месяца назад

    I'm wondering why did you have to use the useFormAction hook? I tried passing my server action directly to the action prop, and it worked for me. Am I missing something here?

    • @Spellkaze
      @Spellkaze 4 месяца назад +1

      The issue with that is that you are not going to get a "message" back from the server, you send the action to the server, it will execute but you won't have a way to get a response and update your ui accordingly

  • @nicovanbockel9945
    @nicovanbockel9945 9 месяцев назад

    Do you have an example of doing this without ShadCn?

  • @firstprincipleslearning
    @firstprincipleslearning 10 месяцев назад

    Hi Jack, awesome content as always. Is there any news on the nextjs course ?

    • @jherr
      @jherr  10 месяцев назад

      It's my full time job. I just released a full tutorial on forms. Should have the first pay-for parts up by the end of March.

    • @firstprincipleslearning
      @firstprincipleslearning 10 месяцев назад

      @@jherr Awesome news ! Can't wait for the release!

  • @sushantjadhav1475
    @sushantjadhav1475 10 месяцев назад

    Excelent video! can you show how to configure Server Actions with xpath?

    • @jherr
      @jherr  10 месяцев назад

      xpath? like the XML search system?

  • @boombang857
    @boombang857 10 месяцев назад +1

    Hm, I get this error:
    Error: A React form was unexpectedly submitted. If you called form.submit() manually, consider using form.requestSubmit() instead. If you're trying to use event.stopPropagation() in a submit event handler, consider also calling event.preventDefault().
    Any idea what might be causing this?

    • @jherr
      @jherr  10 месяцев назад

      I think that's a transient HMR issue. Try hard refreshing the page without a form resubmission.

    • @boombang857
      @boombang857 10 месяцев назад

      Thank you for the suggestion and the excellent videos! I will give it a try. It appears that this approach is not well-supported currently. It seems that to achieve progressive behavior, one should focus on server components and avoid client-side stuff. However, having client-side validation feels so good! I'm sure that this area will evolve as the development of the framework continues. Keep up the great work!@@jherr

    • @APerson-d5s
      @APerson-d5s 10 месяцев назад

      @@boombang857 I am running into this issue, did you find a solution?

    • @drewgoodwin9631
      @drewgoodwin9631 10 месяцев назад

      @@jherr I don't think it is a transient HMR issue-same issue comes back after re-navigating back to the form page. A little research on the web seems to indicate that onSubmit handle is basically not allowed when using an action on the form. Are you sure this method is going to work?

    • @jherr
      @jherr  10 месяцев назад

      @@drewgoodwin9631 Interesting. It was transient for me. I'll add the preventDefault and if that's stable I'll update the project.

  • @ryanbaltazar5795
    @ryanbaltazar5795 10 месяцев назад +1

    hello, im just curious. what if i want to call a toast or something else if the server returns an error?

    • @jherr
      @jherr  10 месяцев назад

      Sure, you just return some data that indicates a toast and then you render the toast based on that. You can even use CSS to fade it out after a reasonable amount of time.

    • @ryanbaltazar5795
      @ryanbaltazar5795 10 месяцев назад

      @@jherr thank you for reply! your tutorial is amazing! i was thinking of using shadcn toast,
      toast("Event has been created", {
      description: "Sunday, December 03, 2023 at 9:00 AM",
      action: {
      label: "Undo",
      onClick: () => console.log("Undo"),
      },
      })
      something like this. how am i gonna call this one?

    • @logconsole-s2f
      @logconsole-s2f 10 месяцев назад

      @@ryanbaltazar5795 I wonder if it is inside useEffect?

    • @jherr
      @jherr  10 месяцев назад +1

      @@ryanbaltazar5795 Feel free to jump onto the Blue Collar Coder Discord server and ask your question there. Please READ and FOLLOW the #rules before posting.

  • @lethanhtu125
    @lethanhtu125 10 месяцев назад

    hey, I don't get the point of passing formData into the server actions and do validations in that. In case I already have a backend API, does it more easier to just pass the input to the server action and send the request to the API server?
    With that I could hide where I send the request to from my users and that the point of use server action. Does it right?

    • @jherr
      @jherr  10 месяцев назад

      I don't understand. Would there be a server action in this model you are proposing? Or are you just posting from the client to your service? Confused.

    • @Divineleo2023
      @Divineleo2023 10 месяцев назад

      ?? Why what you are proposing seems like an additional step ur doing the reverse cause using server action ur just not using backend api in the app router to send request to that external api.
      I feel you added another later of complexity

    • @jherr
      @jherr  10 месяцев назад

      @@Divineleo2023 Well, it's not really ME per se. This is a pretty stock NextJS forms example using server actions. The free tutorial does have API versions. Though I think the state managed by `useFormState` is actually pretty nice. You'd have to manage your own without that, and you'd have to plumb the state back to the original route from the post to get the JavaScript disabled functionality.

    • @lethanhtu125
      @lethanhtu125 10 месяцев назад

      @@jherr yes, in the server action function, I just take the form input and sent a request to the backend api and let the backend do the validation

  • @siya.abc123
    @siya.abc123 10 месяцев назад

    I'll never understand limiting next.js (full stack framework) to server actions. Use apis? No?

  • @goatslayer5957
    @goatslayer5957 10 месяцев назад +1

    AWESOME!!!

  • @juttameerhamza
    @juttameerhamza 8 месяцев назад

    How can I check pending state of form ?

  • @waltervanwoudenberg6876
    @waltervanwoudenberg6876 8 месяцев назад +1

    This does not seem to be working with the latest versions/releases
    Next: 14.2.3
    React: 18.3.1
    React hook form: 7.51.4
    Hook form resolvers: 3.3.4
    Zod: 3.23.8

    • @jherr
      @jherr  8 месяцев назад

      What does “not working” mean? What happens versus what you expect.

    • @waltervanwoudenberg6876
      @waltervanwoudenberg6876 8 месяцев назад +1

      @@jherr sorry, it does not even get to the server action when I log the values in there

  • @melkhywong7594
    @melkhywong7594 10 месяцев назад

    this is GOLD!

  • @shaunmodipane1
    @shaunmodipane1 10 месяцев назад

    What if we have a multipage form?

  • @marius-mihailionte339
    @marius-mihailionte339 10 месяцев назад

    Do you plan to add paid courses on the pronextjs platform aiming for e2e project development?

    • @jherr
      @jherr  10 месяцев назад

      Yes.

  • @richardokonicha
    @richardokonicha 4 месяца назад

    we should crown him king.

  • @trietcao1368
    @trietcao1368 10 месяцев назад

    I can't use server action with form have field upload image ... :(

    • @alexisjaimez7439
      @alexisjaimez7439 10 месяцев назад

      ruclips.net/video/5L5YoFm1obk/видео.htmlsi=3vKi-MzTswKSrC69

  • @vasiliskarantousis
    @vasiliskarantousis 5 месяцев назад

    Thank you so much!

  • @Balance-8
    @Balance-8 10 месяцев назад

    How do you add loading states?

    • @ruanxun9454
      @ruanxun9454 10 месяцев назад +1

      I have the same questions since I don't know why but using useFormStatus in a child button is not working. Currently I just use a useState called isSubmitting and manually update it during onSubmit, before formRef.current?.submit() and after it. Like this:
      onSubmit={form.handleSubmit(async () => {
      setIsSubmitting(true)
      formRef.current?.submit()
      setIsSubmitting(false)
      })}

  • @KamalSingh-zo1ol
    @KamalSingh-zo1ol 8 месяцев назад

    Where is the formdata type coming from?

    • @jherr
      @jherr  8 месяцев назад

      It's a built in type.

  • @tcmjr
    @tcmjr 2 месяца назад

    For those stuck like me. This approach wont work for complex shadcn like switch, select ... They will not be submited to the server action. You need to use onSubmit handler only for those.

  • @mertdr
    @mertdr 10 месяцев назад

    I think “works even if JS disabled” was a bad marketing plan for a front-end first JS framework. I guess what Vercel and React team trying to pull off is, even JS interactivity is not your first priority, you can still build pages like PHP or similar backend languages (currently what Astro does with official React solution). In other words, steps up and makes a bold move in order to have a better position in the market. NextJS is not taken seriously as a backend solution although it’s a fullstack meta framework. I believe these improvements might change that.
    By the way a great tutorial as always Jack. Too much boilerplate IMO and I believe soon there will be a more compact solution (by the help of react hook forms I hope) but it’s good to know we’re getting there.

    • @rumble1925
      @rumble1925 10 месяцев назад +1

      Progressive enhancement should have been a priority from the start imo.

  • @nickwoodward819
    @nickwoodward819 6 месяцев назад

    so wait, do I need to upgrade to react 19 if I'm using nextjs app router, or nah?

    • @jherr
      @jherr  6 месяцев назад

      You've been on React 19 the entire time if you've been on the App Router. 🤯

    • @nickwoodward819
      @nickwoodward819 6 месяцев назад

      @@jherr weird! my package.json say 18.3? 🧐

    • @nickwoodward819
      @nickwoodward819 6 месяцев назад

      are we counting from zero? what am I doing wrong? 😂

    • @jherr
      @jherr  6 месяцев назад

      @@nickwoodward819 Next is weird. It actually has it's own copy of the React canary built in that it uses for the App Router. 18.3 is there for Pages router compatibility.

    • @nickwoodward819
      @nickwoodward819 6 месяцев назад

      @@jherr Interest to know! I was kinda hoping that would explain the error I'm getting when adding back in the rhf handleSubmit function back into the mix
      Error: Invalid hook call (pointing at null useRef)
      Hooks can only be called inside of the body of a function component.
      Reason 3 is "you might have more than one copy of React in the same app" :D

  • @hardwired66
    @hardwired66 10 месяцев назад +1

    Mantine form tutorial pls sir

  • @richardokonicha
    @richardokonicha 4 месяца назад

    our hero

  • @skapator
    @skapator 10 месяцев назад +39

    I do not get it. How is this usable in real senarios?. What I am I missing here? This seems like we are back in the 2000s. What is the issue we are solving ? Multi-step, conditional fields, dynamic fields... this is going to be a maintenance hell in my mind. I am not getting the value proposition of nextjs here. There are clearly better battle tested ways for this.

    • @frankyang1834
      @frankyang1834 10 месяцев назад +3

      i haven't watched the full video yet, but for people who are new to react and next.js every new feature is like another level of abstraction, so it is always better than nothing

    • @Tommy-ev6gv
      @Tommy-ev6gv 10 месяцев назад +10

      What do you mean? This demo shows how can you get client/server-side validation using RHF, Zod and React. You don't have to use Nextjs, but it's a popular fullstack framework.

    • @mertdr
      @mertdr 10 месяцев назад +2

      This is how react prepares to cover larger ground and step into backend game more and more. But of course I agree with you about larger multi step forms. This won’t be much of help. But for example a simple job application form or contact form will be working no matter what even visitor’s disabled JS. First thing NextJS solved was fixing empty html pages through SSR. And now server actions and helper hooks. It’s pretty new concept and obviously needs more time to become a mature solution. Yet they’re doing a pretty solid job IMO.

    • @Pete133
      @Pete133 10 месяцев назад +1

      Not sure what you’re comparing this setup to because you don’t say, but it’s a lot easier than how you would do it in the older versions of next.js. Of course there are easier ways to make a simple form… you don’t have to do all this in next.js either. But if you want client and server validation with nice error messages then this setup is easy to replicate and gets you a long way for the amount of code required.

    • @Pete133
      @Pete133 10 месяцев назад +1

      Was there a way of getting both client-side and server-side validation and custom error messages with this little code in the 2000’s? (HTML validation doesn’t count as client side validation).
      Also how does this make maintenance harder? Genuinely asking to see if I can help explain or learn something.

  • @davidkhierl696
    @davidkhierl696 9 месяцев назад

    this is completely incorrect as the browser will reload in the code provided. RHF is still drafting the support for server action. in the meantime I suggest to use form.trigger() on the onSubmit prop instead of a form ref submit

    • @sebap_xc
      @sebap_xc 8 месяцев назад

      form.trigger() is not a function.. But yes it reloads. Any fix?

    • @davidkhierl696
      @davidkhierl696 8 месяцев назад

      @@sebap_xc on the useForm there is a trigger function

  • @0xAndy
    @0xAndy 10 месяцев назад +1

    I like how you explain things but I don't like this pattern and it feels unwieldy for complex form or multi form scenarios.

  • @Technology_Forum
    @Technology_Forum 10 месяцев назад

    how do you highligth a particular line of code or block of code during presentation what settings or command do yo use