Search code examples
javascripthtmlreactjsremix.run

Remix Submit Object


What's the right way of submitting object in remix using useSubmit()? Do i need to JSON.stringify() it first? Then JSON.parse() it in the action?

My code below is working but not sure if its the best way?

onSubmit()

const onSubmit = () => {

    const updatedContact = {
        name: "John Doe",
        email: "",
    };

    const updatedOrder = {
        products: [
            {
                id: 1,
                name: "Product 1",
                quantity: 1,
            },
            {
                id: 2,
                name: "Product 2",
                quantity: 2,
            },
        ],
        total: 100,
    };

    const product = JSON.stringify(updatedContact);
    const order = JSON.stringify({
        updatedOrder: updatedOrder,
    });

    const formData = {
        id,
        product,
        order,
    };

    submit(formData, { method: "post", encType: "multipart/form-data" });
};

action

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

    const {
        id,
        product,
        order,
    } = Object.fromEntries(formData) as {
        [k: string]: string;
    };

    console.log({
        id,
        product: JSON.parse(product),
        order: JSON.parse(order),
    })

};

Solution

  • You can now use JSON directly instead of always using form data.

    submit({ id, product, order }, { method: 'post', encType: 'appliction/json' })
    
    function action({ request} ) {
      const { id, product, order } = await request.json()
      //...
    }
    

    https://remix.run/docs/en/main/hooks/use-submit#options