- Fix shipping cost not included in checkout total - Add useShippingMethodSelector hook for proper abstraction - Remove blocking initCheckout from Header for better performance - Checkout now initializes lazily when cart opens or item added
74 lines
2.0 KiB
TypeScript
74 lines
2.0 KiB
TypeScript
"use client";
|
|
|
|
import { useCallback } from "react";
|
|
import { createCheckoutService } from "@/lib/services/checkoutService";
|
|
|
|
interface UseShippingMethodSelectorOptions {
|
|
checkoutId: string | null;
|
|
onSelect: (methodId: string) => void;
|
|
onRefresh: () => Promise<void>;
|
|
}
|
|
|
|
interface UseShippingMethodSelectorResult {
|
|
selectShippingMethod: (methodId: string) => Promise<void>;
|
|
selectShippingMethodWithApi: (methodId: string) => Promise<void>;
|
|
}
|
|
|
|
/**
|
|
* Hook to manage shipping method selection
|
|
* Encapsulates both UI state update and API communication
|
|
* Used for both manual selection (user click) and auto-selection (default method)
|
|
*/
|
|
export function useShippingMethodSelector(
|
|
options: UseShippingMethodSelectorOptions
|
|
): UseShippingMethodSelectorResult {
|
|
const { checkoutId, onSelect, onRefresh } = options;
|
|
|
|
/**
|
|
* Updates UI state only (for initial/pre-selection)
|
|
*/
|
|
const selectShippingMethod = useCallback(
|
|
async (methodId: string) => {
|
|
onSelect(methodId);
|
|
},
|
|
[onSelect]
|
|
);
|
|
|
|
/**
|
|
* Updates UI state AND calls Saleor API
|
|
* Use this when user manually selects OR when auto-selecting the default
|
|
*/
|
|
const selectShippingMethodWithApi = useCallback(
|
|
async (methodId: string) => {
|
|
if (!checkoutId) {
|
|
console.warn("[selectShippingMethodWithApi] No checkoutId provided");
|
|
return;
|
|
}
|
|
|
|
// Update UI immediately for responsiveness
|
|
onSelect(methodId);
|
|
|
|
// Call API through CheckoutService
|
|
const checkoutService = createCheckoutService(checkoutId);
|
|
const result = await checkoutService.updateShippingMethod(methodId);
|
|
|
|
if (result.success) {
|
|
// Refresh checkout to get updated totals including shipping
|
|
await onRefresh();
|
|
} else {
|
|
console.error(
|
|
"[selectShippingMethodWithApi] Failed to update shipping method:",
|
|
result.error
|
|
);
|
|
// Could add error handling/rollback here
|
|
}
|
|
},
|
|
[checkoutId, onSelect, onRefresh]
|
|
);
|
|
|
|
return {
|
|
selectShippingMethod,
|
|
selectShippingMethodWithApi,
|
|
};
|
|
}
|