Skip to content

Commit

Permalink
Merge pull request #267 from haines/handle-non-object-loader-data
Browse files Browse the repository at this point in the history
Handle non-object loader data in `useDefaultValuesFromLoader`
  • Loading branch information
airjp73 authored Apr 8, 2023
2 parents 0da58ae + 502eb01 commit ae27716
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 1 deletion.
28 changes: 28 additions & 0 deletions apps/test-app/app/routes/non-object-loader-data.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { json, DataFunctionArgs } from "@remix-run/node";
import { withZod } from "@remix-validated-form/with-zod";
import { ValidatedForm } from "remix-validated-form";
import { zfd } from "zod-form-data";
import { Input } from "~/components/Input";
import { SubmitButton } from "~/components/SubmitButton";

const validator = withZod(
zfd.formData({
text1: zfd.text(),
})
);

export type LoaderData = string;

export const loader = (args: DataFunctionArgs) =>
json<LoaderData>("Hello, world");

export default function FrontendValidation() {
return (
<>
<ValidatedForm validator={validator} method="post" id="test-form">
<Input name="text1" type="text" label="Text" />
<SubmitButton />
</ValidatedForm>
</>
);
}
5 changes: 5 additions & 0 deletions apps/test-app/cypress/integration/default-values.ts
Original file line number Diff line number Diff line change
Expand Up @@ -98,4 +98,9 @@ describe("Validation", () => {
'"defaultChecked": false'
);
});

it("should not fail when encountering non-object loader data", () => {
cy.visit("/non-object-loader-data").waitForJs();
cy.findByLabelText("Text").should("have.value", "");
});
});
5 changes: 4 additions & 1 deletion packages/remix-validated-form/src/internal/hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,10 @@ export const useDefaultValuesFromLoader = ({
// we should use the data from the deepest route.
const match = matches
.reverse()
.find((match) => match.data && dataKey in match.data);
.find(
(match) =>
match.data && typeof match.data === "object" && dataKey in match.data
);
return match?.data[dataKey];
}

Expand Down

1 comment on commit ae27716

@vercel
Copy link

@vercel vercel bot commented on ae27716 Apr 8, 2023

Choose a reason for hiding this comment

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

Please sign in to comment.