Reputation: 11
When trying to get data from the prisma.order.findmany() table, in development mode we get the correct data, in production mode we get the data only at the initialization stage of the project.
useOrders.ts
import { useState, useEffect } from 'react';
import { Order } from '@prisma/client';
export const useOrders = () => {
const [orders, setOrders] = useState<Order[]>([]);
const [filteredOrders, setFilteredOrders] = useState<Order[]>([]);
const [statusFilter, setStatusFilter] = useState<string>('ALL');
const [searchId, setSearchId] = useState<string>('');
const fetchOrders = async () => {
try {
console.log('[USE-ORDERS-FETCH] Fetching orders...');
const res = await fetch(`/api/admin/orders?timestamp=${Date.now()}`, {
headers: {
'Content-Type': 'application/json',
},
});
if (!res.ok) {
throw new Error(`[USE-ORDERS-FETCH] HTTP error! status: ${res.status}`);
}
const data = await res.json();
console.log('[USE-ORDERS-FETCH] Fetched orders:', data);
setOrders(data);
console.log('[USE-ORDERS-FETCH] Orders state updated:', data);
} catch (error) {
console.error('[USE-ORDERS-FETCH] Error fetching orders:', error);
}
};
const updateOrder = async (orderId: string, field: string, value: string) => {
try {
const response = await fetch(`/api/admin/orders/${orderId}`, {
method: 'PATCH',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ [field]: value }),
});
if (!response.ok) {
const error = await response.json();
throw new Error(error.error || '[USE-ORDERS-UPDATE] Failed to update order');
}
await fetchOrders();
console.log('[USE-ORDERS-UPDATE] Order updated:', orderId, field, value);
} catch (error) {
console.error('[USE-ORDERS-UPDATE] Error updating order:', error);
}
};
useEffect(() => {
fetchOrders();
console.log('[USE-ORDERS-USEEFFECT] Orders:', orders);
}, []);
useEffect(() => {
if (statusFilter === 'ALL') {
setFilteredOrders(
searchId
? orders.filter(order => order.orderId.toString().includes(searchId))
: orders
);
} else {
setFilteredOrders(
orders.filter(order =>
order.status === statusFilter &&
(searchId ? order.orderId.toString().includes(searchId) : true)
)
);
}
}, [statusFilter, orders, searchId]);
return {
orders,
filteredOrders,
statusFilter,
setStatusFilter,
searchId,
setSearchId,
updateOrder,
};
};
app/api/admin/orders/route.ts
import { prisma } from '@/prisma/prisma-client';
import { NextRequest, NextResponse } from 'next/server';
export async function GET(request: NextRequest) {
try {
let orders = await prisma.order.findMany({
orderBy: {
createdAt: 'desc'
}
});
console.log('[API-ADMIN-ORDERS-GET] Orders:', orders);
return NextResponse.json(orders, {
headers: {
'Cache-Control': 'no-store, no-cache, must-revalidate, proxy-revalidate',
'Pragma': 'no-cache',
'Expires': '0',
},
});
} catch (error) {
console.error('[API-ADMIN-ORDERS] Orders API Error:', error);
return NextResponse.json({ error: '[API-ADMIN-ORDERS] Внутренняя ошибка сервера' }, { status: 500 });
}
}
outputs logs in development mode, but not in production mode. at the same time, the logs /api/admin/orders/${OrderID} are passed in both dev and prod
app\api\admin\orders[id]\route.ts
import { prisma } from '@/prisma/prisma-client';
import { NextRequest, NextResponse } from 'next/server';
export async function PATCH(
request: NextRequest,
{ params }: { params: { id: string } }
) {
try {
const body = await request.json();
const orderId = parseInt(params.id);
if (isNaN(orderId)) {
return NextResponse.json(
{ error: '[API-ADMIN-ORDERS-PATCH] Invalid order ID' },
{ status: 400 }
);
}
const updatedOrder = await prisma.order.update({
where: { id: orderId },
data: body,
});
console.log('[API-ADMIN-ORDERS-PATCH] Updated order:', updatedOrder);
return NextResponse.json(updatedOrder);
} catch (error) {
console.error('[API-ADMIN-ORDERS-PATCH] Update Order API Error:', error);
return NextResponse.json(
{ error: '[API-ADMIN-ORDERS-PATCH] Ошибка при обновлении заказа' },
{ status: 500 }
);
}
}
changes do occur in the database, but prisma returns a response with a 200 status, and the data that was at the first initialization of the project (only in production mode, in development mode current). here are screenshots from network and supbase
in this case, I changed the status from "COMPLETED" to "PENDING", these changes were correctly changed in supbase, but after the request /api/admin/orders/, the data before the change is returned to us, the status is 200. even if I refresh the page, a new request is made, it still returns the old data.
I thought maybe the problem was in nginx or middleware, but removing them completely led to the same results.
Upvotes: 0
Views: 22