fix: store api

This commit is contained in:
paolosantarsiero 2025-05-20 16:57:38 +02:00
parent b250d83534
commit d5dee1c261
5 changed files with 39 additions and 26 deletions

View File

@ -38,7 +38,10 @@ export async function POST(req: NextRequest) {
return NextResponse.json(cart, { status: 200 });
} catch (error) {
return NextResponse.json(
{ error: 'Failed to add item to cart', message: JSON.stringify(error) },
{
error: 'Failed to add item to cart',
message: JSON.stringify(error)
},
{ status: 500 }
);
}

View File

@ -10,6 +10,7 @@ export default function CheckoutReview() {
const { checkout } = useCheckout();
const handleCreateOrder = async () => {
try {
const order = await fetch('/api/customer/order', {
method: 'POST',
body: JSON.stringify({
@ -17,9 +18,15 @@ export default function CheckoutReview() {
shipping_address: checkout?.shipping,
payment_method: checkout?.payment_method
})
}).catch((err) => {
console.error('Error creating order', err);
});
if (!order.ok) {
const errorData = await order.json();
console.error('Error creating order:', errorData);
throw new Error(errorData.error || 'Failed to create order');
}
} catch (error) {
console.error('Error creating order', error);
}
};
return (
<section className="mt-4 grid w-full gap-4 px-4 pb-4">

View File

@ -20,7 +20,8 @@ import Bg2 from '../assets/images/slide-bg-02.webp';
async function Products({ category }: { category: Category }) {
const products: Product[] = await woocommerce.get('products', {
category: category.id.toString()
category: category.id.toString(),
author: 1, // Use admin user to get all products
});
return <ThreeItemGrid products={products} />;

View File

@ -5,7 +5,6 @@ import clsx from 'clsx';
import { useProduct } from 'components/product/product-context';
import { Product, ProductVariations } from 'lib/woocomerce/models/product';
import { useTranslations } from 'next-intl';
import { toast } from 'sonner';
import { useCart } from './cart-context';
function SubmitButton({ disabled = false }: { disabled: boolean }) {
@ -45,18 +44,18 @@ export function AddToCart({
return (
<form
action={async () => {
try {
const cart = await (
await fetch('/api/cart', {
const response = await fetch('/api/cart', {
method: 'POST',
body: JSON.stringify({ id: product.id, quantity: 1, variation })
})
).json();
setNewCart(cart);
toast('Item added to cart');
} catch (error) {
console.error(error);
});
if (!response.ok) {
console.error('Error adding to cart');
return;
}
const cart = await response.json();
setNewCart(cart);
}}
>
<SubmitButton disabled={variations?.length && !state.variation ? true : false} />

View File

@ -45,8 +45,9 @@ function createStoreApiClient({
method,
url: baseURL + url,
data,
headers
headers,
});
return response;
} catch (error: any) {
if (error.response) {
@ -55,8 +56,9 @@ function createStoreApiClient({
console.debug('Token expired, regenerating...');
const newAuthToken = await regenerateAuthToken();
headers.Authorization = `Bearer ${newAuthToken}`;
return _request(method, url, data);
return _request(method, url, data); // Retry the request with the new token
}
throw new Error(
`Request failed with status ${error.response.status}: ${error.response.data.message}`
);
@ -76,6 +78,7 @@ function createStoreApiClient({
params?: Record<string, string | number>
): Promise<{ cart: Cart; cartToken?: string }> {
const res = await _request('get', '/cart', { params });
return { cart: res.data, cartToken: res.headers['cart-token'] };
},