Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve TypeScript inference for common action pattern #3878

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions packages/remix-react/__tests__/hook-types-test.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
import * as React from "react";
import type { ActionArgs } from "@remix-run/node";
import { json, redirect } from "@remix-run/node";

import type { TypedResponse, UseDataFunctionReturn } from "../components";
import { useActionData } from "../components";

function isEqual<A, B>(
arg: A extends B ? (B extends A ? true : false) : false
Expand Down Expand Up @@ -111,3 +116,35 @@ describe("type serializer", () => {
isEqual<response, { arg1: string; arg2?: number }>(true);
});
});

describe("actual usage", () => {
it("should support typical action usage", () => {
async function action({ request }: ActionArgs) {
let formData = await request.formData();
let email = formData.get("email");
let password = formData.get("password");
if (typeof email !== "string" || !email) {
return json({ errors: { email: "Email is required" } });
}
if (typeof password !== "string" || !password) {
return json({ errors: { password: "Password is required" } });
}
return redirect("/hooray");
}

// eslint-disable-next-line @typescript-eslint/no-unused-vars
function Component() {
let actionData = useActionData<typeof action>();

React.useEffect(() => {
if (actionData?.errors?.email) {
// focus email
} else if (actionData?.errors?.password) {
// focus password
}
Comment on lines +140 to +144
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note: this test technically runs fine, but fails TypeScript on these two if statements.

}, [actionData]);

return <div>UI</div>;
}
});
});
1 change: 1 addition & 0 deletions packages/remix-react/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
"type-fest": "^2.17.0"
},
"devDependencies": {
"@remix-run/node": "1.6.6-pre.1",
"@testing-library/jest-dom": "^5.16.2",
"@testing-library/react": "^12.1.3",
"abort-controller": "^3.0.0",
Expand Down