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.
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');
};