1

I'm trying the React Router tutorial in TypeScript. The code works but I find it hard to identify the parameters' type definitions, e.g.

export async function action({ request, params }) {
    const formData = await request.formData();
    const updates = Object.fromEntries(formData);
...

From debugging I can see the variable request is a type of Request, however I can't find such a type when trying to import.

A similar question regarding the params parameter.

Can someone help a confused .NET C# dev here, please?

Lin Du
  • 88,126
  • 95
  • 281
  • 483
user3928256
  • 903
  • 1
  • 11
  • 17

2 Answers2

4

Aside from action, none of these APIs we're discussing are provided by React Router: request, request.formData, Object.fromEntries are all provided by the web platform.

Request is an interface of the Fetch API, see https://developer.mozilla.org/en-US/docs/Web/API/Request

It is defined in the node_modules/typescript/lib/lib.dom.d.ts file.

params:

Route params are parsed from dynamic segments and passed to your loader

params TS type should be defined by the user. We can get it using the useParams hook.

So the complete TS version of action should be:

type MyParams = {
  contactId: string;
}
async function action({ request, params }: { request: Request; params: MyParams; }) {}
Lin Du
  • 88,126
  • 95
  • 281
  • 483
2

You can use ActionFunction from react-router. That way, the types of the arguments are inferred correctly:

import { redirect } from "react-router-dom";
import type { ActionFunction } from "react-router";

export const action: ActionFunction = async ({ request, params }) => {
  const formData = await request.formData();
  const updates = Object.fromEntries(formData);
  await updateContact(params.contactId, updates);
  return redirect(`/contacts/${params.contactId}`);
}

If you want to type the arguments directly instead of the function you could use ActionFunctionArgs from react-router but I don't see an advantage of doing that.

(Using the type LoaderFunction for the loader method works exactly the same.)

iron9
  • 397
  • 2
  • 12