Skip to content

Commit

Permalink
feat: test input error in comment example
Browse files Browse the repository at this point in the history
  • Loading branch information
bholmesdev committed May 3, 2024
1 parent 8b8819b commit 7ec4d5b
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ export default {
input: z.object({
postId: z.string(),
author: z.string(),
body: z.string(),
body: z.string().min(50),
}),
handler: async ({ postId, author, body }) => {
const comment = await db.insert(Comment).values({
Expand Down
Original file line number Diff line number Diff line change
@@ -1,24 +1,32 @@
import { getNameProps, actions } from "astro:actions";
import { getNameProps, actions, isInputError } from "astro:actions";
import { useState } from "react";

export function PostComment({postId}: {postId: string}) {
const [comments, setComments] = useState<{ author: string, body: string }[]>([]);
const [bodyError, setBodyError] = useState<string | undefined>(undefined);

return (
<>
<form method="POST" onSubmit={async (e) => {
e.preventDefault();
const form = e.target as HTMLFormElement;
const formData = new FormData(form);
const {comment} = await actions.blog.comment(formData);
setComments(c => [comment, ...c]);
const { data, error } = await actions.blog.comment.safe(formData);
if (isInputError(error)) {
return setBodyError(error.fields.body?.join(' '));
}
if (data) {
setBodyError(undefined);
setComments(c => [data.comment, ...c]);
}
form.reset();
}}>
<input {...getNameProps(actions.blog.comment)} />
<input type="hidden" name="postId" value={postId} />
<label className="sr-only" htmlFor="author">Author</label>
<input id="author" type="text" name="author" placeholder="Your name" />
<textarea rows={10} name="body"></textarea>
{bodyError && <p style={{ color: 'red' }}>{bodyError}</p>}
<button type="submit">Post</button>
</form>
{comments.map(c => (
Expand Down

0 comments on commit 7ec4d5b

Please sign in to comment.