shadcn and server actions example?
Answered
Acacia-ants posted this in #help-forum
Original message was deleted.
Answered by Ray
function onSubmit(e: FormEvent<HTMLFormElement>) {
const formData = new FormData(e.currentTarget)
form.handleSubmit(async () => {
await formAction(formData)
form.reset()
})(e)
}22 Replies
Original message was deleted
you should use action props and onSubmit props together. action props provide the fallback support when javascript is disabled.
function onSubmit(e: FormEvent<HTMLFormElement>) {
form.handleSubmit(async () => {
await formAction(new FormData(e.currentTarget))
form.reset()
})()
}
<form
action={formAction}
onSubmit={onSubmit}
/>Original message was deleted
the code wasn't working. i have updated the code
Original message was deleted
no you don't need to do this
function onSubmit(e: FormEvent<HTMLFormElement>) {
e.preventDefault()
form.handleSubmit(async () => {
if (false) {
await formAction(new FormData(e.currentTarget))
form.reset()
}
})()
}try adding preventDefault here
if javascript is availble, it should use onSubmit props, otherwise it will use action props
Original message was deleted
how about this?
function onSubmit(e: FormEvent<HTMLFormElement>) {
const formData = new FormData(e.currentTarget)
e.preventDefault()
form.handleSubmit(async () => {
if (false) {
await formAction(formData)
form.reset()
}
})()
}Original message was deleted
oh I know why
function onSubmit(e: FormEvent<HTMLFormElement>) {
const formData = new FormData(e.currentTarget)
form.handleSubmit(async () => {
await formAction(formData)
form.reset()
})(e)
}Answer
pass e to it
Original message was deleted
what value?
you don't need to check if the form isValid or not inside handleSubmit
handleSubmit should handle it for you
also you don't need to check it in action props too
it doesn't work if javascript is not availble
np
Original message was deleted
useFormStatus doesn't work well with react-hook-formbecause react-hook-form is calling
preventDefault() which make useFormStatus doesn't work properlyaction={formAction}
onSubmit={e => {
form.trigger()
if (form.formState.isValid) {
e.currentTarget.requestSubmit()
} else {
e.preventDefault()
}
}}but there is a way to use it. try this if you want to use
useFormStatusyou should do it on
onSubmit propsyes
Why do you need to use useFormStatus while you can get ‘isSubmitting’ from react-hook-form ?