AddCollection Component (opens in a new tab)
The AddCollection component is a React functional component used to add a new collection to the system.
Usage
<AddCollection />Functionality
The component maintains its own state for the title and disease fields of the new collection. These states are updated whenever the user types into the corresponding input fields.
When the form is submitted, the component sends a POST request to the /api/add_collection endpoint with the title and disease as the request body. The request is made using the react-query library's useMutation hook.
If the request is successful, the component invalidates the 'collections' query in the react-query cache to ensure that the newly added collection is included when the collections data is fetched next time. A success toast notification is also displayed.
If the request fails, an error toast notification is displayed.
After the form is submitted, whether the request is successful or not, the input fields are cleared
POST /api/add_collection endpoint
import { db } from '@/lib/db';
import { collections } from '@/lib/db/schema';
import { NextResponse } from 'next/server';
export const runtime = 'edge';
export const POST = async (req: Request) => {
try {
const { title, disease } = await req.json();
// Insert the values into the "collection" table
await db.insert(collections).values({
title: title,
disease: disease,
});
return NextResponse.json({ message: 'Collection data inserted successfully.' });
} catch (error: any) {
console.error('Error inserting collection data:', error);
return NextResponse.json(
{ error: 'Error inserting collection data.'},
{ status: 500 }
);
}
};
The endpoint is implemented as a POST function in the route.ts file. The function uses the db object from the @/lib/db module to insert the collection data into the collections table in the Neon database. Entry's id and created_at values will be automatically handled by Neon database.
The function uses the NextResponse.json method from the next/server module to return the response. If the collection is added successfully, the response includes a success message. If there's an error, the response includes an error message and a status code of 500.
Structure
The component returns a form with two input fields for the title and disease of the new collection, and a submit button. The form is laid out in a table for alignment.
Styles
The component uses Tailwind CSS for styling. The submit button uses the Button component from the @/components/ui/button module, and includes a plus circle icon from the lucide-react library.
Dependencies
The component depends on the following libraries:
reactfor building the componentreact-queryfor making the POST request and managing the cachereact-hot-toastfor displaying toast notificationslucide-reactfor the plus circle icon@/components/ui/buttonfor the submit button styling