skip to Main Content

How do we get the fields without having to do this individually?

const name = (formData.get("name") ?? "") as string;

Can we map or iterate it?

CODE

export const action: ActionFunction = async ({
    request,
}: ActionFunctionArgs) => {
    const formData = await request.formData();

    const name = (formData.get("name") ?? "") as string;
    const website_url = (formData.get("website_url") ?? "") as string;
    const user_id = (formData.get("user_id") ?? "") as string;

    try {
        // call api here

        return null;
    } catch (error) {
        throw json({ error: "Error" }, { status: 500 });
    }
};

2

Answers


  1. You can use Object.fromEntries() static method and pass your formData object to it it will convert standarad js object.

    Object.fromEntries(formData);
    
    const formData = new FormData();
    formData.set("name","Jhon");
    formData.set("age","30");
    console.log(Object.fromEntries(formData));
    Login or Signup to reply.
  2. you iterate through formData using forEach

    TS palyground

    const formData = new FormData();
    formData.set("name","Jhon");
    formData.set("website_url","https://example.com");
    formData.set("user_id","16546551231");
    
    let allowedFields = ['name','website_url']
    
    let requestPayload = new Map()
    formData.forEach((value,key)=> allowedFields.includes(key) && requestPayload.set(key,value))
    
    let {name, website_url, user_id} = Object.fromEntries(requestPayload)
    console.log(name,website_url,user_id)
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search