Pixtane
Pixtane

Reputation: 74

Running useFormState dispatch with data

I want to validate data from a form before passing it to a server. For this, I want to direct the form action property to a function, which would validate the data on the client side and run the formAction if everything is correct. But I don't understand how to pass data from form action to function and from function to formAction function. I use next.js, typescript. I want to use form state, to have formState variable, but if I call formAction, it doesn't expect any arguments, even though I want to give it my data from form. How to pass data to the validateData function, and then to formAction? I use next.js 14.2.5, react and react-dom 18.2

Here is an MVP of my problem.

"use client";
import { useFormState } from "react-dom";
import farServerFunction from "./func.ts";

export default function Page() {
  const [formState, formAction] = useFormState(farServerFunction, null);
  const validateData = (data: FormData) => {
    const name = data.get("name") as string;
    if (name.length < 5) {
      alert("Name must be at least 5 characters long.");
      return;
    }
    formAction(data); // Expected 0 arguments, but got 1
  }
  return <form action={validateData}>
    <input type="text" name="name" />
    <button type="submit">Submit</button>
  </form>;
}

I tried googling, chatGPT and searching documentation but found it confusing and not enough to understand.

Upvotes: 0

Views: 25

Answers (1)

Pixtane
Pixtane

Reputation: 74

It turns out that useFormState works by adapting to the function you pass inside. So if you pass a test function with nothing inside of it yet, it would have no arguments expected. So the solution is to define the function with necessary arguments (e.g. "_: any, formData: FormData"), and when you pass an argument when you call formAction, it won't raise an error.

Upvotes: 0

Related Questions