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

assignment(validation): Use Remix Validated Form #8

Open
wants to merge 2 commits into
base: tutorial
Choose a base branch
from
Open
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
153 changes: 85 additions & 68 deletions app/routes/posts.admin.new.tsx
Original file line number Diff line number Diff line change
@@ -1,90 +1,107 @@
import type { ActionArgs } from "@remix-run/node";
import { json, redirect } from "@remix-run/node";
import { Form, useActionData, useNavigation } from "@remix-run/react";
import invariant from "tiny-invariant";
import { redirect } from "@remix-run/node";
import { createPost } from "~/models/post.server";

import {
ValidatedForm,
useField,
useIsSubmitting,
validationError,
} from "remix-validated-form";
import { withZod } from "@remix-validated-form/with-zod";
import { z } from "zod";

const inputClassName = `w-full rounded border border-gray-500 px-2 py-1 text-lg`;

export const validator = withZod(
z.object({
title: z.string().min(1, { message: "Title is required" }),
slug: z.string().min(1, { message: "Slug name is required" }),
markdown: z.string().min(1, { message: "Markdown content is required" }),
})
);

export const action = async ({ request }: ActionArgs) => {
const formData = await request.formData();
const result = await validator.validate(await request.formData());

const title = formData.get("title");
const slug = formData.get("slug");
const markdown = formData.get("markdown");
if (result.error) {
return validationError(result.error);
}

await new Promise((res) => setTimeout(res, 1000));

const errors = {
title: title ? null : "Title is required",
slug: slug ? null : "Slug is required",
markdown: markdown ? null : "Markdown is required",
};
await createPost(result.data);

const hasErrors = Object.values(errors).some((errorMessage) => errorMessage);
if (hasErrors) {
return json(errors);
}
return redirect("/posts/admin");
};

export default function NewPost() {
return (
<ValidatedForm method="post" validator={validator}>
<Input name="title" label="Post Title" />
<Input name="slug" label="Post Slug" />

invariant(typeof title === "string", "title must be a string");
invariant(typeof slug === "string", "slug must be a string");
invariant(typeof markdown === "string", "markdown must be a string");
<Textarea name="markdown" label="Markdown" />

await createPost({ title, slug, markdown });
<p className="text-right">
<SubmitButton />
</p>
</ValidatedForm>
);
}

return redirect("/posts/admin");
type InputProps = {
name: string;
label: string;
};

export default function NewPost() {
const errors = useActionData<typeof action>();
export const Input = ({ name, label }: InputProps) => {
const { error, getInputProps } = useField(name);
return (
<p>
<label htmlFor={name}>
{`${label}: `}
{error && <em className="text-red-600">{error}</em>}
<input {...getInputProps({ id: name, className: inputClassName })} />
</label>
</p>
);
};

const navigation = useNavigation();
const isCreating = Boolean(navigation.state === "submitting");
type TextareaProps = {
name: string;
label: string;
};

export const Textarea = ({ name, label }: TextareaProps) => {
const { error, getInputProps } = useField(name);
return (
<Form method="post">
<p>
<label>
Post Title:{" "}
{errors?.title ? (
<em className="text-red-600">{errors.title}</em>
) : null}
<input type="text" name="title" className={inputClassName} />
</label>
</p>
<p>
<label>
Post Slug:{" "}
{errors?.slug ? (
<em className="text-red-600">{errors.slug}</em>
) : null}
<input type="text" name="slug" className={inputClassName} />
</label>
</p>
<p>
<label htmlFor="markdown">
Markdown:
{errors?.markdown ? (
<em className="text-red-600">{errors.markdown}</em>
) : null}
</label>
<br />
<p>
<label htmlFor={name}>
{`${label}: `}
{error && <em className="text-red-600">{error}</em>}
<textarea
id="markdown"
rows={20}
name="markdown"
className={`${inputClassName} font-mono`}
{...getInputProps({
id: name,
rows: 20,
className: `${inputClassName} font-mono`,
})}
/>
</p>
<p className="text-right">
<button
type="submit"
className="rounded bg-blue-500 px-4 py-2 text-white hover:bg-blue-600 focus:bg-blue-400 disabled:bg-blue-300"
disabled={isCreating}
>
{isCreating ? "Creating..." : "Create Post"}
</button>
</p>
</Form>
</label>
</p>
);
}
};

export const SubmitButton = () => {
const isSubmitting = useIsSubmitting();

return (
<button
type="submit"
className="rounded bg-blue-500 px-4 py-2 text-white hover:bg-blue-600 focus:bg-blue-400 disabled:bg-blue-300"
disabled={isSubmitting}
>
{isSubmitting ? "Creating..." : "Create Post"}
</button>
);
};
Loading