mirror of
https://github.com/vercel/next-learn.git
synced 2026-06-11 09:51:47 +00:00
Remove routes and actions
This commit is contained in:
@@ -10,15 +10,10 @@ import {
|
||||
} from '@heroicons/react/24/outline';
|
||||
import { Button } from '../button';
|
||||
import { createInvoice } from '@/app/lib/actions';
|
||||
// @ts-ignore React types do not yet include useFormState
|
||||
import { experimental_useFormState as useFormState } from 'react-dom';
|
||||
|
||||
export default function Form({ customers }: { customers: CustomerField[] }) {
|
||||
const initialState = { message: null, errors: [] };
|
||||
const [state, dispatch] = useFormState(createInvoice, initialState);
|
||||
|
||||
return (
|
||||
<form action={dispatch}>
|
||||
<form>
|
||||
<div className="rounded-md bg-gray-50 p-4 md:p-6">
|
||||
{/* Customer Name */}
|
||||
<div className="mb-4">
|
||||
|
||||
@@ -31,7 +31,6 @@ export default async function InvoicesTable({
|
||||
className="mr-2 rounded-full"
|
||||
width={28}
|
||||
height={28}
|
||||
alt={`${invoice.name}'s profile picture`}
|
||||
/>
|
||||
<p>{invoice.name}</p>
|
||||
</div>
|
||||
@@ -90,7 +89,6 @@ export default async function InvoicesTable({
|
||||
className="rounded-full"
|
||||
width={28}
|
||||
height={28}
|
||||
alt={`${invoice.name}'s profile picture`}
|
||||
/>
|
||||
<p>{invoice.name}</p>
|
||||
</div>
|
||||
|
||||
@@ -1,5 +0,0 @@
|
||||
import DashboardSkeleton from '@/app/ui/dashboard/skeletons';
|
||||
|
||||
export default function Loading() {
|
||||
return <DashboardSkeleton />;
|
||||
}
|
||||
@@ -1,33 +0,0 @@
|
||||
import Cards from '@/app/ui/dashboard/cards';
|
||||
import RevenueChart from '@/app/ui/dashboard/revenue-chart';
|
||||
import LatestInvoices from '@/app/ui/dashboard/latest-invoices';
|
||||
import { lusitana } from '@/app/ui/fonts';
|
||||
import { Suspense } from 'react';
|
||||
import {
|
||||
RevenueChartSkeleton,
|
||||
LatestInvoicesSkeleton,
|
||||
CardsSkeleton,
|
||||
} from '@/app/ui/dashboard/skeletons';
|
||||
|
||||
export default async function Page() {
|
||||
return (
|
||||
<main>
|
||||
<h1 className={`${lusitana.className} mb-4 text-xl md:text-2xl`}>
|
||||
Dashboard
|
||||
</h1>
|
||||
<div className="grid gap-6 sm:grid-cols-2 lg:grid-cols-4">
|
||||
<Suspense fallback={<CardsSkeleton />}>
|
||||
<Cards />
|
||||
</Suspense>
|
||||
</div>
|
||||
<div className="mt-6 grid grid-cols-1 gap-6 md:grid-cols-4 lg:grid-cols-8">
|
||||
<Suspense fallback={<RevenueChartSkeleton />}>
|
||||
<RevenueChart />
|
||||
</Suspense>
|
||||
<Suspense fallback={<LatestInvoicesSkeleton />}>
|
||||
<LatestInvoices />
|
||||
</Suspense>
|
||||
</div>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -1,21 +0,0 @@
|
||||
import { fetchFilteredCustomers } from '@/app/lib/data';
|
||||
import CustomersTable from '@/app/ui/customers/table';
|
||||
|
||||
export default async function Page({
|
||||
searchParams,
|
||||
}: {
|
||||
searchParams?: {
|
||||
query?: string;
|
||||
page?: string;
|
||||
};
|
||||
}) {
|
||||
const query = searchParams?.query || '';
|
||||
|
||||
const customers = await fetchFilteredCustomers(query);
|
||||
|
||||
return (
|
||||
<main>
|
||||
<CustomersTable customers={customers} />
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -1,18 +0,0 @@
|
||||
import Link from 'next/link';
|
||||
import { FaceFrownIcon } from '@heroicons/react/24/outline';
|
||||
|
||||
export default function NotFound() {
|
||||
return (
|
||||
<main className="flex h-full flex-col items-center justify-center gap-2">
|
||||
<FaceFrownIcon className="w-10 text-gray-400" />
|
||||
<h2 className="text-xl font-semibold">404 Not Found</h2>
|
||||
<p>Could not find the requested invoice.</p>
|
||||
<Link
|
||||
href="/dashboard/invoices"
|
||||
className="mt-4 rounded-md bg-blue-500 px-4 py-2 text-sm text-white transition-colors hover:bg-blue-400"
|
||||
>
|
||||
Go Back
|
||||
</Link>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -1,32 +0,0 @@
|
||||
import Form from '@/app/ui/invoices/edit-form';
|
||||
import Breadcrumbs from '@/app/ui/invoices/breadcrumbs';
|
||||
import { fetchInvoiceById, fetchCustomers } from '@/app/lib/data';
|
||||
import { notFound } from 'next/navigation';
|
||||
|
||||
export default async function Page({ params }: { params: { id: string } }) {
|
||||
const id = params.id;
|
||||
const [invoice, customers] = await Promise.all([
|
||||
fetchInvoiceById(id),
|
||||
fetchCustomers(),
|
||||
]);
|
||||
|
||||
if (!invoice) {
|
||||
notFound();
|
||||
}
|
||||
|
||||
return (
|
||||
<main>
|
||||
<Breadcrumbs
|
||||
breadcrumbs={[
|
||||
{ label: 'Invoices', href: '/dashboard/invoices' },
|
||||
{
|
||||
label: 'Edit Invoice',
|
||||
href: `/dashboard/invoices/${id}/edit`,
|
||||
active: true,
|
||||
},
|
||||
]}
|
||||
/>
|
||||
<Form invoice={invoice} customers={customers} />
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -1,23 +0,0 @@
|
||||
import { fetchCustomers } from '@/app/lib/data';
|
||||
import Form from '@/app/ui/invoices/create-form';
|
||||
import Breadcrumbs from '@/app/ui/invoices/breadcrumbs';
|
||||
|
||||
export default async function Page() {
|
||||
const customers = await fetchCustomers();
|
||||
|
||||
return (
|
||||
<main>
|
||||
<Breadcrumbs
|
||||
breadcrumbs={[
|
||||
{ label: 'Invoices', href: '/dashboard/invoices' },
|
||||
{
|
||||
label: 'Create Invoice',
|
||||
href: '/dashboard/invoices/create',
|
||||
active: true,
|
||||
},
|
||||
]}
|
||||
/>
|
||||
<Form customers={customers} />
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -1,31 +0,0 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect } from 'react';
|
||||
|
||||
export default function Error({
|
||||
error,
|
||||
reset,
|
||||
}: {
|
||||
error: Error & { digest?: string };
|
||||
reset: () => void;
|
||||
}) {
|
||||
useEffect(() => {
|
||||
// Optionally log the error to an error reporting service
|
||||
console.error(error);
|
||||
}, [error]);
|
||||
|
||||
return (
|
||||
<main className="flex h-full flex-col items-center justify-center">
|
||||
<h2 className="text-center">Something went wrong!</h2>
|
||||
<button
|
||||
className="mt-4 rounded-md bg-blue-500 px-4 py-2 text-sm text-white transition-colors hover:bg-blue-400"
|
||||
onClick={
|
||||
// Attempt to recover by trying to re-render the invoices route
|
||||
() => reset()
|
||||
}
|
||||
>
|
||||
Try again
|
||||
</button>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -1,40 +0,0 @@
|
||||
import Pagination from '@/app/ui/invoices/pagination';
|
||||
import Search from '@/app/ui/search';
|
||||
import Table from '@/app/ui/invoices/table';
|
||||
import { CreateInvoice } from '@/app/ui/invoices/buttons';
|
||||
import { lusitana } from '@/app/ui/fonts';
|
||||
import { InvoicesTableSkeleton } from '@/app/ui/dashboard/skeletons';
|
||||
import { Suspense } from 'react';
|
||||
import { fetchInvoicesPages } from '@/app/lib/data';
|
||||
|
||||
export default async function Page({
|
||||
searchParams,
|
||||
}: {
|
||||
searchParams?: {
|
||||
query?: string;
|
||||
page?: string;
|
||||
};
|
||||
}) {
|
||||
const query = searchParams?.query || '';
|
||||
const currentPage = Number(searchParams?.page) || 1;
|
||||
|
||||
const totalPages = await fetchInvoicesPages(query);
|
||||
|
||||
return (
|
||||
<div className="w-full">
|
||||
<div className="flex w-full items-center justify-between">
|
||||
<h1 className={`${lusitana.className} text-2xl`}>Invoices</h1>
|
||||
</div>
|
||||
<div className="mt-4 flex items-center justify-between gap-2 md:mt-8">
|
||||
<Search placeholder="Search invoices..." />
|
||||
<CreateInvoice />
|
||||
</div>
|
||||
<Suspense key={query + currentPage} fallback={<InvoicesTableSkeleton />}>
|
||||
<Table query={query} currentPage={currentPage} />
|
||||
</Suspense>
|
||||
<div className="mt-5 flex w-full justify-center">
|
||||
<Pagination totalPages={totalPages} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
import SideNav from '@/app/ui/dashboard/sidenav';
|
||||
|
||||
export default function Layout({ children }: { children: React.ReactNode }) {
|
||||
return (
|
||||
<div className="flex h-screen flex-col md:flex-row md:overflow-hidden">
|
||||
<div className="w-full flex-none md:w-64">
|
||||
<SideNav />
|
||||
</div>
|
||||
<div className="flex-grow p-6 md:overflow-y-auto md:p-12">{children}</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,121 +0,0 @@
|
||||
'use server';
|
||||
|
||||
import { z } from 'zod';
|
||||
import { sql } from '@vercel/postgres';
|
||||
import { revalidatePath } from 'next/cache';
|
||||
import { redirect } from 'next/navigation';
|
||||
|
||||
const FormSchema = z.object({
|
||||
id: z.string(),
|
||||
customerId: z.string({
|
||||
invalid_type_error: 'Please select a customer.',
|
||||
}),
|
||||
amount: z.coerce
|
||||
.number()
|
||||
.gt(0, { message: 'Please enter an amount greater than $0.' }),
|
||||
status: z.enum(['pending', 'paid'], {
|
||||
invalid_type_error: 'Please select an invoice status.',
|
||||
}),
|
||||
date: z.string(),
|
||||
});
|
||||
|
||||
const CreateInvoice = FormSchema.omit({ id: true, date: true });
|
||||
const UpdateInvoice = FormSchema.omit({ date: true });
|
||||
const DeleteInvoice = FormSchema.pick({ id: true });
|
||||
|
||||
// This is temporary
|
||||
export type State = {
|
||||
errors?: {
|
||||
customerId?: string[];
|
||||
amount?: string[];
|
||||
status?: string[];
|
||||
};
|
||||
message: string;
|
||||
};
|
||||
|
||||
export async function createInvoice(prevState: State, formData: FormData) {
|
||||
// Validate form fields using Zod
|
||||
const validatedFields = CreateInvoice.safeParse({
|
||||
customerId: formData.get('customerId'),
|
||||
amount: formData.get('amount'),
|
||||
status: formData.get('status'),
|
||||
});
|
||||
|
||||
// If form validation fails, return errors early. Otherwise, continue.
|
||||
if (!validatedFields.success) {
|
||||
return {
|
||||
errors: validatedFields.error.flatten().fieldErrors,
|
||||
message: 'Missing Fields. Failed to Create Invoice.',
|
||||
};
|
||||
}
|
||||
|
||||
// Prepare data for insertion into the database
|
||||
const { customerId, amount, status } = validatedFields.data;
|
||||
const amountInCents = amount * 100;
|
||||
const date = new Date().toISOString().split('T')[0];
|
||||
|
||||
// Insert data into the database
|
||||
try {
|
||||
await sql`
|
||||
INSERT INTO invoices (customer_id, amount, status, date)
|
||||
VALUES (${customerId}, ${amountInCents}, ${status}, ${date})
|
||||
`;
|
||||
} catch (error) {
|
||||
// If a database error occurs, return a more specific error.
|
||||
return {
|
||||
message: 'Database Error: Failed to Create Invoice.',
|
||||
};
|
||||
}
|
||||
|
||||
// Revalidate the cache for the invoices page and redirect the user.
|
||||
revalidatePath('/dashboard/invoices');
|
||||
redirect('/dashboard/invoices');
|
||||
}
|
||||
|
||||
export async function updateInvoice(prevState: State, formData: FormData) {
|
||||
const validatedFields = UpdateInvoice.safeParse({
|
||||
id: formData.get('id'),
|
||||
customerId: formData.get('customerId'),
|
||||
amount: formData.get('amount'),
|
||||
status: formData.get('status'),
|
||||
});
|
||||
|
||||
if (!validatedFields.success) {
|
||||
return {
|
||||
errors: validatedFields.error.flatten().fieldErrors,
|
||||
message: 'Missing Fields. Failed to Update Invoice.',
|
||||
};
|
||||
}
|
||||
|
||||
const { id, customerId, amount, status } = validatedFields.data;
|
||||
const amountInCents = amount * 100;
|
||||
|
||||
try {
|
||||
await sql`
|
||||
UPDATE invoices
|
||||
SET customer_id = ${customerId}, amount = ${amountInCents}, status = ${status}
|
||||
WHERE id = ${id}
|
||||
`;
|
||||
} catch (error) {
|
||||
return { message: 'Database Error: Failed to Update Invoice.' };
|
||||
}
|
||||
|
||||
revalidatePath('/dashboard/invoices');
|
||||
redirect('/dashboard/invoices');
|
||||
}
|
||||
|
||||
export async function deleteInvoice(formData: FormData) {
|
||||
// throw new Error('Failed to Delete Invoice');
|
||||
|
||||
const { id } = DeleteInvoice.parse({
|
||||
id: formData.get('id'),
|
||||
});
|
||||
|
||||
try {
|
||||
await sql`DELETE FROM invoices WHERE id = ${id}`;
|
||||
revalidatePath('/dashboard/invoices');
|
||||
return { message: 'Deleted Invoice' };
|
||||
} catch (error) {
|
||||
return { message: 'Database Error: Failed to Delete Invoice.' };
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,6 @@
|
||||
"scripts": {
|
||||
"build": "next build",
|
||||
"dev": "next dev",
|
||||
"lint": "next lint",
|
||||
"seed": "node -r dotenv/config ./scripts/seed.js",
|
||||
"start": "next start"
|
||||
},
|
||||
|
||||
Reference in New Issue
Block a user