Next.js Discord

Discord Forum

How to pass arguments in useFormState in server action?

Unanswered
Almond stone wasp posted this in #help-forum
Open in Discord
Avatar
Almond stone waspOP
I am trying to pass an argument using useFormState
const EmailForm = () => {
  const initialState = {errors : {}, message : null, data  : undefined};
  const SendEmail = sendEmail.bind(null, selectLink );
  const [state, formAction] = useFormState(SendEmail, initialState);
  
return(
  <form action={SendEmail}>
    ////// 
    //////
  </fomr>
)
}


export type State = {
    errors?: {
        from ?: string[] | undefined;
        to ?: string[] | undefined;
        subject?: string[] | undefined;
        message?: string[] | undefined;
      };
    message?: string | null;
    data : undefined;
}


// action
export async function sendEmail(selectLink : string, prevState : State, formData : FormData){

    const validateFields =  sendEmailFormSchema.safeParse({
        from : formData.get('from'),
        to : formData.get('to'),
        subject : formData.get('subject'),
        message : formData.get('message'),
    })

}


// getting this error
o overload matches this call. Overload 1 of 2, '(action: (state: Error | { errors: { to?: string[] | undefined; from?: string[] | undefined; message?: string[] | undefined; subject?: string[] | undefined; }; message: string; data: undefined; } | { ...; } | { ...; }) => Error | ... 3 more ... | Promise<...>, initialState: Error | ... 2 more ... | { ...; }, permalink?: string | undefined): [state: ...]', gave the following error. Argument of type '(prevState: State, formData: FormData) => Promise<Error | { errors: { to?: string[] | undefined; from?: string[] | undefined; message?: string[]

3 Replies

Avatar
Ray
like you did
the error is complaining the typeof state
try
const EmailForm = () => {
  const SendEmail = sendEmail.bind(null, selectLink );
  const initialState = {errors : {}, message : null, data  : undefined} as Awaited<ReturnType<typeof SendEmail>>;
  const [state, formAction] = useFormState(SendEmail, initialState);
  
return(
  <form action={SendEmail}>
    ////// 
    //////
  </fomr>
)
}