Skip to content

Commit

Permalink
Separate Server Action File
Browse files Browse the repository at this point in the history
  • Loading branch information
mirkonasato committed Nov 27, 2023
1 parent 4fea761 commit 03ccd8f
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 20 deletions.
20 changes: 20 additions & 0 deletions app/reviews/[slug]/actions.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
'use server';

import { revalidatePath } from 'next/cache';
import { redirect } from 'next/navigation';
import { createComment } from '@/lib/comments';

export async function createCommentAction(formData) {
if (!formData.get('user')) {
return { isError: true, message: 'Name field is required' };
}
const data = {
slug: formData.get('slug'),
user: formData.get('user'),
message: formData.get('message'),
};
const comment = await createComment(data);
console.log('created:', comment);
revalidatePath(`/reviews/${data.slug}`);
redirect(`/reviews/${data.slug}`);
}
24 changes: 4 additions & 20 deletions components/CommentForm.jsx
Original file line number Diff line number Diff line change
@@ -1,31 +1,15 @@
// 'use client';
'use client';

import { revalidatePath } from 'next/cache';
import { redirect } from 'next/navigation';
import { createComment } from '@/lib/comments';
import { createCommentAction } from '@/app/reviews/[slug]/actions';

export default function CommentForm({ slug, title }) {
async function action(formData) {
'use server';
if (!formData.get('user')) {
return { isError: true, message: 'Name field is required' };
}
const comment = await createComment({
slug,
user: formData.get('user'),
message: formData.get('message'),
});
console.log('created:', comment);
revalidatePath(`/reviews/${slug}`);
redirect(`/reviews/${slug}`);
}

return (
<form action={action}
<form action={createCommentAction}
className="border bg-white flex flex-col gap-2 mt-3 px-3 py-3 rounded">
<p className="pb-1">
Already played <strong>{title}</strong>? Have your say!
</p>
<input type="hidden" name="slug" value={slug} />
<div className="flex">
<label htmlFor="userField" className="shrink-0 w-32">
Your name
Expand Down

0 comments on commit 03ccd8f

Please sign in to comment.