commerce icon indicating copy to clipboard operation
commerce copied to clipboard

usePrice throws error with Typescript

Open vicasas opened this issue 3 years ago • 3 comments

Using the usePrice hook doing destructuring to use price basePrice and discount this throws a Typescript error.

const { price, basePrice, discount } = usePrice({
    amount: product.offerPrice,
    baseAmount: product.price,
    currencyCode: 'CLP',
  })

const basePrice: any Property 'basePrice' does not exist on type '{ price: string; basePrice: string | null; discount: string | null; } | { price: string; }'.ts(2339)

vicasas avatar Feb 16 '22 11:02 vicasas

export default function usePrice(
  data?: {
    amount: number
    baseAmount?: number
    currencyCode: string
  } | null
) {
  const { amount, baseAmount, currencyCode } = data ?? {}
  const { locale } = useCommerce()
  const value = useMemo(() => {
    if (typeof amount !== 'number' || !currencyCode) return ''

    return baseAmount
      ? formatVariantPrice({ amount, baseAmount, currencyCode, locale })
      : formatPrice({ amount, currencyCode, locale })
  }, [amount, baseAmount, currencyCode])

  return typeof value === 'string' ? { price: value } : value
}

mauriciofragajr avatar Feb 26 '22 06:02 mauriciofragajr

@mauriciofragajr I do not understand. The error occurs precisely because of that function, since it returns two different objects and when typesript destructuring is used, it does not understand what the function returns.

vicasas avatar Feb 26 '22 14:02 vicasas

We're going to check it! Thanks for reporting.

okbel avatar Mar 23 '22 15:03 okbel

Hey there! Thank you for opening this issue. We have decided to take Next.js Commerce in a new direction and will be closing out current PRs and issues due to this change. Please see this PR for more details: https://github.com/vercel/commerce/pull/966

leerob avatar Apr 18 '23 02:04 leerob