lib/useAvailability.js
/**
 * Custom hook for getting product availability
 * @param {string} id
 * @param {string} permalink
 * @returns product availability
 */
Custom hook for getting product availability
@param {string} id
@param {string} permalink
@returns product availability
Custom hook for getting product availability @param { string } id @param { string } permalink @returns product availability
function useAvailability(id, permalink) {
    const { data, error } = useSWR(permalink, fetcher, { refreshInterval: 30 });
    const inCart = useSelector((state) => state?.cart?.line_items?.find(item => item?.product_id === id)?.quantity || 0);
    const defaultInventory = useSelector((state) => state?.products?.find(product => product?.id === id)?.inventory);
    if (error) {
      console.error('Error fetching product availability for product', id, permalink, error);
      return { left: 0, inCart };
    }
    if (!data) {
      if (defaultInventory) {
        const left = defaultInventory.managed ? defaultInventory.available : 10;
        return { left, inCart };
      }
    }
    const inventory = data ? data.inventory : { managed: false, available: 10 };
    const left = inventory.managed ? inventory.available : 10;
    return { left, inCart };
}
function useAvailability ( id , permalink ) { const { data , error } = useSWR ( permalink , fetcher , { refreshInterval : 30 } ) ; const inCart = useSelector ( ( state ) => state ?. cart ?. line_items ?. find ( item => item ?. product_id === id ) ?. quantity || 0 ) ; const defaultInventory = useSelector ( ( state ) => state ?. products ?. find ( product => product ?. id === id ) ?. inventory ) ; if ( error ) { console . error ( 'Error fetching product availability for product' , id , permalink , error ) ; return { left : 0 , inCart } ; } if ( ! data ) { if ( defaultInventory ) { const left = defaultInventory . managed ? defaultInventory . available : 10 ; return { left , inCart } ; } } const inventory = data ? data . inventory : { managed : false , available : 10 } ; const left = inventory . managed ? inventory . available : 10 ; return { left , inCart } ; }
Custom hook for getting product availability
 @param {string} id
 @param {string} permalink
 @returns product availability
Custom hook for getting product availability @param { string } id @param { string } permalink @returns product availability
/** @constant @type {number} */ /** @constant @type {Inventory} */ // console.error('Error fetching product availability, data is undefined for product:', id, permalink); // return { left: 0, inCart };