#Remix Form. How to get all fields from dynamic form?

1 messages · Page 1 of 1 (latest)

atomic vortex
#

I have multiple dynamic forms on the client that use this component

<Form method="post">
        <Flex>
          <Button type="submit">Create {model}  </Button>
          <Button>Read {model}</Button>
          <Button>Update {model}</Button>
          <Button>Delete {model}</Button>
        </Flex>
        {Object.keys(fields).map((key) => (
          <Input
            key={key}
            name={key}
            placeholder={"Insert " + key}
          />
        ))}
      </Form>

The Inputs are dynamic and I want to process the values on the server onSubmit.

The docs show we can get values using the get function:

export const action = async ({ request}) => {
  const form = await request.formData();
  console.log(form.get("name"));
  return json({ message: `test` });
};

But how do I get all the values without hardcoding the "name" key

#

Found the solution

export const action = async ({ request}) => {
  const form = await request.formData();
  console.log(Object.fromEntries(form));
  return json({ message: `test` });
};
remote axle
#

Assuming all the input names are unique:

const formData = await request.formData();
const formInputs = Object.fromEntries(formData);

#

The only downside here is if you have input arrays, the work around is a write custom function.

remote axle
#

Something like.

const form = await request.formData();
const formInputs = getFormData(form);


const getFormData = (formData) => {

    let params = {};

    const keys = Array.from(formData.keys());
    
    keys.forEach(key => {
        params[key] = formData.getAll(key);
    })

    return params;

}
#

There's probably a more elegant way to write this with map.