skip to Main Content

Working with a remix project which is trying to receive data from the form. When I receive the form data from my React component, I am unable to retrieve any fields from formData.get.

Here is my code in the route,

export async function action(data: any) {
    const { request } = data;

    console.log(`request`);
    console.log(request);

    const formData = await request.formData();

    console.log(`formData`);
    console.log(formData);
    
    const noteData: Note = {
        title: formData.get("title")?.toString() ?? "",
        description: formData.get("description")?.toString() ?? "",
    };
    const note = createNote(noteData);
    console.log(`New note created => Note - ${JSON.stringify(note)}`);
}

Above I have added some log statements as well. Noticing that formData is returning an empty object.

formData
formData {}

How can this be fixed so that I can retrieve the form data?

EDIT:
Adding the React Component below which uses the action,

    export default function Note() {
        return (
            <form method="post" action="/notes" id="quote-form">
                <p>
                    <label htmlFor="title">Title</label>
                    <input type="text" id="title" name="title" required />
                </p>
                <p>
                    <label htmlFor="content">Content</label>
                    <textarea id="content" name="content" required />
                </p>
                <div>
                    <button> Add Note </button>
                </div>
            </form>
        );

}

The route is shown above with the function name action.

2

Answers


  1. request.formData returns a Promise, await it.

    Example:

    export async function action(data: any) {
      const { request } = data;
    
      ...
    
      const formData = await request.formData();
    
      ...
    }
    
    Login or Signup to reply.
  2. Make you function async and await the form data:

    export async function action(data: any) {
        const { request } = data;
    
        console.log(`request`);
        console.log(request);
    
        const formData = await request.formData();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search