Below is a complete implementation for adding a "Create New Post" feature to the existing blog application. This includes both backend mutations and frontend form handling with sample content.
────────────────────────────────────────
UPDATE BACKEND (Apollo Server)
────────────────────────────────────────
1.1 Update typeDefs (server/src/graphql/typeDefs.js)
(Add this inside your existing typeDefs)
graphql Copy code
input PostInput {
title: String!
content: String!
author: String!
}
type Mutation {
addPost(post: PostInput!): Post!
}
1.2 Update Resolvers (server/src/graphql/resolvers.js)
javascript Copy code
Mutation: {
addPost: async (_, { post }) => {
const db = await connectDB();
const { insertedId } = await db.collection("posts").insertOne(post);
return { _id: insertedId, ...post };
},
},
────────────────────────────────────────
2. UPDATE FRONTEND (Next.js)
────────────────────────────────────────
2.1 Create Post Form Component
/components/CreatePostForm.tsx
tsx Copy code
import { useState } from "react";
import { useMutation } from "@apollo/client";
import { gql } from "@apollo/client";
import { GET_POSTS } from "../graphql/queries";
const ADD_POST = gql`
mutation AddPost($post: PostInput!) {
addPost(post: $post) {
_id
title
author
}
}
`;
const sampleContents = [
{
title: "10 JavaScript Tips",
author: "John Doe",
content: `1. Use optional chaining: foo?.bar
2. Nullish coalescing: x ?? y
3. Template literals: \`Hello \$\{name\}\`
4. Destructuring assignment...`
},
{
title: "CSS Grid Mastery",
author: "Jane Smith",
content: `The \`grid\` property is a shorthand for:
- grid-template-rows
- grid-template-columns
- grid-template-areas
Example:
\`\`\`css
.container {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 1rem;
}
\`\`\``
},
// Add more samples...
];
export default function CreatePostForm() {
const [addPost] = useMutation(ADD_POST, {
refetchQueries: [GET_POSTS], // Update list after create
});
const [formData, setFormData] = useState({
title: "",
author: "",
content: "",
});
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
try {
await addPost({ variables: { post: formData } });
setFormData({ title: "", author: "", content: "" });
} catch (error) {
console.error("Error creating post:", error);
}
};
return (
<div className="max-w-2xl mx-auto mb-10">
<h2 className="text-2xl font-bold mb-4">Create New Post</h2>
<form onSubmit={handleSubmit} className="space-y-4">
<div>
<label className="block font-medium">Title</label>
<input
type="text"
value={formData.title}
onChange={(e) => setFormData({ ...formData, title: e.target.value })}
required
className="w-full p-2 border rounded mt-1"
/>
</div>
<div>
<label className="block font-medium">Author</label>
<input
type="text"
value={formData.author}
onChange={(e) => setFormData({ ...formData, author: e.target.value })}
required
className="w-full p-2 border rounded mt-1"
/>
</div>
<div>
<label className="block font-medium">Content</label>
<textarea
value={formData.content}
onChange={(e) => setFormData({ ...formData, content: e.target.value })}
required
rows={6}
className="w-full p-2 border rounded mt-1"
/>
</div>
<div className="flex justify-between items-center">
<button
type="submit"
className="bg-indigo-600 text-white px-4 py-2 rounded hover:bg-indigo-700"
>
Publish Post
</button>
<div className="space-x-2">
{sampleContents.map((sample, index) => (
<button
key={index}
type="button"
onClick={() => setFormData(sample)}
className="text-sm text-gray-600 hover:text-indigo-600"
>
Demo {index + 1}
</button>
))}
</div>
</div>
</form>
</div>
);
}
2.2 Add Form to Homepage
Update /pages/index.tsx
tsx Copy code
// ... existing imports
import CreatePostForm from "../components/CreatePostForm";
export default function Home() {
// ... existing code
return (
<div className="max-w-4xl mx-auto p-4">
<CreatePostForm /> {/* Add this line */}
<h1 className="text-4xl font-bold mb-6 text-center">📝 Blog Posts</h1>
{/* ... existing post list */}
</div>
);
}
────────────────────────────────────────
3. SAMPLE CONTENT DEMOS
────────────────────────────────────────
Clicking "Demo 1", "Demo 2", etc. will auto-fill:
Demo 1
Title: 10 JavaScript Tips
Author: John Doe
Content:
code Copy code
1. Use optional chaining: foo?.bar
2. Nullish coalescing: x ?? y
3. Template literals: `Hello ${name}`
4. Destructuring assignment...
Demo 2
Title: CSS Grid Mastery
Author: Jane Smith
Content:
code Copy code
The `grid` property is a shorthand for:
- grid-template-rows
- grid-template-columns
- grid-template-areas
Example:
```css
.container {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 1rem;
}
code Copy code
**Demo 3**
Title: React Hooks Explained
Author: Alice Johnson
Content:
useState: Manage component state
useEffect: Handle side effects
useContext: Consume context values
useRef: Create mutable references
Example:
jsx Copy code
function Counter() {
const [count, setCount] = useState(0);
return <button onClick={() => setCount(count + 1)}>{count}</button>;
}
code Copy code
────────────────────────────────────────
4. TRY IT OUT
────────────────────────────────────────
1. Restart both servers if needed
2. Go to http://localhost:3000
3. Fill the form manually or click a "Demo X" button
4. Click "Publish Post"
5. New post should appear in the list
The form includes:
• Real-time input validation
• Auto-fill for demo content
• Mutation with automatic list update
• Responsive Tailwind styling
Let me know if you need help with:
• Adding validation rules
• Implementing debounced auto-save
• Adding rich text editor
• Deploying to production