Код: Выделить всё
import { Suspense } from "react";
import { UserIdPageWrapper } from "./_components/userId-page-wrapper";
interface UserIdPageProps {
params: Promise;
}
export const dynamic = "force-dynamic";
export default async function UserIdPage({ params }: UserIdPageProps) {
const { userId } = await params;
return (
);
}
Код: Выделить всё
import { db } from "@/lib/db";
import { UserInfo } from "./userInfo";
import { redirect } from "next/navigation";
interface UserIdPageWrapperProps {
userId: string;
}
export const UserIdPageWrapper = async ({ userId }: UserIdPageWrapperProps) => {
const [userData, paymentsData] = await Promise.all([
db.user.findUnique({
where: {
id: userId,
},
}),
db.payment.findMany({
where: {
userId: userId,
},
include: {
items: true,
},
}),
]);
if (!userData || !paymentsData) {
redirect("/");
}
return (
);
};
br />
Код: Выделить всё
"use client";
import { useRouter } from "next/navigation";
import { useState } from "react";
import toast from "react-hot-toast";
interface userInfoProps {
user: User;
payments: (Payment & { items: PaymentItem[] })[];
}
export const UserInfo = ({ user, payments }: userInfoProps) => {
const router = useRouter();
const [isLoading, setIsLoading] = useState(false);
const handleAddPayment = async () => {
setIsLoading(true);
try {
const res = await fetch("/api/payments", {
method: "POST",
body: JSON.stringify({
userId: user.id,
totalAmount: 0,
supervisionRatio: 0,
}),
headers: {
"Content-Type": "application/json",
},
});
if (!res.ok) {
throw new Error("Failed to add payment");
}
const jsonData = await res.json();
console.log(jsonData);
toast.success("New payment added");
router.refresh();
} catch (error) {
toast.error("Failed to add payment");
} finally {
setIsLoading(false);
}
};
// ... rest of the component
};
Код: Выделить всё
import { NextResponse } from "next/server";
import { db } from "@/lib/db";
export async function POST(req: Request) {
try {
const { userId, totalAmount, supervisionRatio } = await req.json();
const res = await db.payment.create({
data: {
userId,
totalAmount,
supervisionRatio,
supervisionFee: (totalAmount * supervisionRatio) / 100,
paymentDate: new Date(),
remainingAmount: totalAmount - (totalAmount * supervisionRatio) / 100,
},
});
return NextResponse.json(res);
} catch (error) {
console.error("[ORDERS_POST]", error);
return new NextResponse("Internal error", { status: 500 });
}
}
Что я пробовал: < /strong> < /p>
- Использование router.refresh () < /code> после Запрос сообщения.
- Настройка dynamic = "force-dynamic" в page.tsx file.
Что я ожидаю:
После создания нового платежа я ожидаю, что компонент платежа для повторного рендеринга с обновленным списком платежей без полного обновления браузера.
Вопрос: < /strong> < /p>
Чего мне не хватает? Есть ли проблема кэширования, или Router.refresh () Не правильный подход для этого сценария? Как я могу гарантировать, что страница обновляется с новыми данными после запроса POST?
Подробнее здесь: https://stackoverflow.com/questions/794 ... st-request