Skip to content

Commit

Permalink
Crate NewPost component
Browse files Browse the repository at this point in the history
  • Loading branch information
milanpanin committed Sep 30, 2024
1 parent 2b57ad5 commit 05a22ec
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 42 deletions.
46 changes: 4 additions & 42 deletions app/page.tsx
Original file line number Diff line number Diff line change
@@ -1,50 +1,12 @@
// app/posts/page.js
import PostsList from '@/components/PostList';
import { query } from '../lib/db';
import { revalidatePath } from 'next/cache';
import NewPost from '@/components/NewPost';

export default function PostsPage() {
async function savePost(formData: { get: (arg0: string) => any; }) {
'use server';

const title = formData.get('title');
const description = formData.get('description');

if (!title || !description) {
throw new Error('Both title and description are required');
}

try {
await query('INSERT INTO posts (title, description) VALUES ($1, $2)', [
title,
description,
]);

revalidatePath('/');
} catch (error) {
console.error('Error saving post:', error);
throw new Error('Failed to save the post.');
}
}

return (
<div>
<main>
<PostsList />
<h1>Create a New Post</h1>
<form action={savePost}>
<input
type="text"
name="title"
placeholder="Title"
required
/>
<textarea
name="description"
placeholder="Description"
required
/>
<button type="submit">Save Post</button>
</form>
</div>
<NewPost />
</main>
);
}
47 changes: 47 additions & 0 deletions components/NewPost.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import { query } from '../lib/db';
import { revalidatePath } from 'next/cache';

export default function NewPost() {
async function savePost(formData: { get: (arg0: string) => any; }) {
'use server';

const title = formData.get('title');
const description = formData.get('description');

if (!title || !description) {
throw new Error('Both title and description are required');
}

try {
await query('INSERT INTO posts (title, description) VALUES ($1, $2)', [
title,
description,
]);

revalidatePath('/');
} catch (error) {
console.error('Error saving post:', error);
throw new Error('Failed to save the post.');
}
}

return (
<div>
<h1>Create a New Post</h1>
<form action={savePost}>
<input
type="text"
name="title"
placeholder="Title"
required
/>
<textarea
name="description"
placeholder="Description"
required
/>
<button type="submit">Save Post</button>
</form>
</div>
);
}

0 comments on commit 05a22ec

Please sign in to comment.