Next.js Discord

Discord Forum

Not getting form data

Answered
Mugger Crocodile posted this in #help-forum
Open in Discord
Mugger CrocodileOP
Server action:
export async function createCharacter(
  formData: FormData
): Promise<CharacterFormState> {
  console.log(formData);
  const result = characterSchema.safeParse({
    name: formData.get("name"),
    nickname: formData.get("nickname"),
  });
  ...

Page:
import CharacterForm from "@/components/character-form";
import { createCharacter } from "../actions/characters";

export default function Page() {
  return (
    <div>
      <h2>Create your character</h2>
      <CharacterForm
        formAction={createCharacter}
        initialData={{ name: "", nickname: "" }}
      ></CharacterForm>
    </div>
  );
}


Form component:
"use client";

import { useFormState } from "react-dom";

interface FormErrors {
  name?: string[];
  nickname?: string[];
}

interface FormState {
  errors: FormErrors;
}

interface CharacterFormProps {
  formAction: any;
  initialData: {
    name: string;
    nickname: string;
  };
}
export default function CharacterForm({
  formAction,
  initialData,
}: CharacterFormProps) {
  const [formState, action] = useFormState<FormState>(formAction, {
    errors: {},
  });

  return (
    <>
      <form action={action}>
        <input type="text" name="name" id="name" />
        {formState.errors.name && <p>{formState.errors.name.join(", ")}</p>}
        <input type="text" name="nickname" id="nickname" />
        {formState.errors.nickname && (
          <p>{formState.errors.nickname.join(", ")}</p>
        )}
        <button type="submit">Save</button>
      </form>
    </>
  );
}


I get
{ errors: {} }
in the console instead of form data. What am I doing wrong?
Answered by Mugger Crocodile
Fuck! The problem was that I removed prevState parameter from the action function
View full answer

4 Replies

by console, you meant browser console? check your vscode console
@James4u by console, you meant browser console? check your vscode console
Mugger CrocodileOP
no, in vs console. I checked the output because initially I got an error that there is no "get" method for formData
Mugger CrocodileOP
Fuck! The problem was that I removed prevState parameter from the action function
Answer