UNPKG

@commercelayer/react-components

Version:
2 lines 2.17 kB
"use client"; import{jsx as _jsx,Fragment as _Fragment}from"react/jsx-runtime";import{useContext,useState,useEffect}from"react";import ShipmentContext from"../../context/ShipmentContext";import ShipmentChildrenContext from"../../context/ShipmentChildrenContext";import getLoaderComponent from"../../utils/getLoaderComponent";import OrderContext from"../../context/OrderContext";export function Shipment({children,loader="Loading...",autoSelectSingleShippingMethod=!1}){const[loading,setLoading]=useState(!0),{shipments,deliveryLeadTimes,setShippingMethod}=useContext(ShipmentContext),{order}=useContext(OrderContext);useEffect(()=>(shipments!=null&&(autoSelectSingleShippingMethod?(async()=>{for(const shipment of shipments){const isSingle=shipment?.available_shipping_methods?.length===1;if(!shipment?.shipping_method&&isSingle){const[shippingMethod]=shipment?.available_shipping_methods||[];if(shippingMethod&&setShippingMethod!=null){const{success,order:order2}=await setShippingMethod(shipment.id,shippingMethod.id);typeof autoSelectSingleShippingMethod=="function"&&success&&autoSelectSingleShippingMethod(order2)}}else setTimeout(()=>{setLoading(!1)},200)}})():setLoading(!1)),()=>{setLoading(!0)}),[shipments!=null,shipments?.length,order?.gift_card_or_coupon_code]);const components=shipments?.map((shipment,k)=>{const lineItems=shipment.stock_line_items?.map(shipmentLineItem=>{const l=shipmentLineItem.line_item;return l&&(l.quantity=shipmentLineItem.quantity),l}),shippingMethods=shipment.available_shipping_methods,currentShippingMethodId=autoSelectSingleShippingMethod&&shippingMethods&&shippingMethods.length===1?shippingMethods[0]?.id:shipment.shipping_method?.id,stockTransfers=shipment.stock_transfers,parcels=shipment.parcels,times=deliveryLeadTimes?.filter(time=>time.stock_location?.id===shipment.stock_location?.id),shipmentProps={parcels,lineItems,shippingMethods,currentShippingMethodId,stockTransfers,deliveryLeadTimes:times,shipment,keyNumber:shipment?.id};return _jsx(ShipmentChildrenContext.Provider,{value:shipmentProps,children},k)});return loading?getLoaderComponent(loader):_jsx(_Fragment,{children:components})}export default Shipment;