Skip to content

Commit

Permalink
Fix useMoney with long language code (#1132)
Browse files Browse the repository at this point in the history
  • Loading branch information
wizardlyhel authored Jul 21, 2023
1 parent c39411e commit 0d2e5ff
Show file tree
Hide file tree
Showing 3 changed files with 74 additions and 1 deletion.
5 changes: 5 additions & 0 deletions .changeset/cyan-cats-unite.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@shopify/hydrogen-react': patch
---

Fix long language code breaking useMoney hook - Contributed by @QuentinGibson
66 changes: 66 additions & 0 deletions packages/hydrogen-react/src/useMoney.test.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import {describe, expect, it} from 'vitest';
import {renderHook} from '@testing-library/react';
import {ShopifyProvider, ShopifyProviderProps} from './ShopifyProvider.js';
import {useMoney} from './useMoney.js';

describe(`useMoney`, () => {
Expand Down Expand Up @@ -62,4 +63,69 @@ describe(`useMoney`, () => {
withoutTrailingZerosAndCurrency: '19',
});
});

it(`does not fail when language ISO code is more than 2 characters`, () => {
const SHOPIFY_CONFIG: ShopifyProviderProps = {
storeDomain: 'https://notashop.myshopify.com',
storefrontToken: 'abc123',
storefrontApiVersion: '2023-07',
countryIsoCode: 'BR',
languageIsoCode: 'PT_PT',
};

const {result} = renderHook(
() =>
useMoney({
amount: '19.00',
currencyCode: 'USD',
}),
{
wrapper: ({children}) => (
<ShopifyProvider
{...SHOPIFY_CONFIG}
storeDomain="https://notashop.myshopify.com"
>
{children}
</ShopifyProvider>
),
},
);

expect(result.current).toEqual({
amount: '19,00 ',
currencyCode: 'USD',
currencyName: 'dólares dos Estados Unidos',
currencyNarrowSymbol: '$',
currencySymbol: 'US$',
localizedString: '19,00 US$',
original: {
amount: '19.00',
currencyCode: 'USD',
},
parts: [
{
type: 'integer',
value: '19',
},
{
type: 'decimal',
value: ',',
},
{
type: 'fraction',
value: '00',
},
{
type: 'literal',
value: ' ',
},
{
type: 'currency',
value: 'US$',
},
],
withoutTrailingZeros: '19 US$',
withoutTrailingZerosAndCurrency: '19',
});
});
});
4 changes: 3 additions & 1 deletion packages/hydrogen-react/src/useMoney.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,9 @@ export type UseMoneyValue = {
*/
export function useMoney(money: MoneyV2): UseMoneyValue {
const {countryIsoCode, languageIsoCode} = useShop();
const locale = `${languageIsoCode}-${countryIsoCode}`;
const locale = languageIsoCode.includes('_')
? languageIsoCode.replace('_', '-')
: `${languageIsoCode}-${countryIsoCode}`;

if (!locale) {
throw new Error(
Expand Down

0 comments on commit 0d2e5ff

Please sign in to comment.