Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Correct type for Form component action in react-router-dom

I’m building an app to learn the new React router (v6.14.1) and I’m using typescript.

I’m trying to build a form using the react-router-dom <Form /> component.

I have my code working, but I had to define the action function prop to any, as seen bellow.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

export const createTruck = async ({ request }: any) => {
  const data = await request.formData()

  const submission = {
    make: data.get('make'),
    model: data.get('model'),
    plate: data.get('plate'),
    year: data.get('year'),
    km: data.get('km'),
    buy_date: data.get('buy_date'),
    last_maint: data.get('last_maint'),
    next_maint_d: data.get('next_maint_d'),
    next_maint_km: data.get('next_maint_km'),
  }

  console.log(submission)

  return redirect('/trucks')
}

What is the correct type I should define request as?

>Solution :

The action function is typed as:

/**
 * Route action function signature
 */
export interface ActionFunction {
    (args: ActionFunctionArgs): Promise<Response> | Response | Promise<any> | any;
}

The action args is type ActionFunctionArgs:

/**
 * @private
 * Arguments passed to route loader/action functions.  Same for now but we keep
 * this as a private implementation detail in case they diverge in the future.
 */
interface DataFunctionArgs {
    request: Request;
    params: Params;
}

/**
 * Arguments passed to action functions
 */
export interface ActionFunctionArgs extends DataFunctionArgs {
}

The ActionFunctionArgs is the type you want to import and specify if your Typescript configuration can’t already infer the correct type.

Example:

import { redirect } from 'react-router-dom';
import type { ActionFunctionArgs } from 'react-router-dom';

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

  const submission = {
    make: data.get('make'),
    model: data.get('model'),
    plate: data.get('plate'),
    year: data.get('year'),
    km: data.get('km'),
    buy_date: data.get('buy_date'),
    last_maint: data.get('last_maint'),
    next_maint_d: data.get('next_maint_d'),
    next_maint_km: data.get('next_maint_km'),
  };

  console.log(submission);

  return redirect('/trucks');
};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading