Skip to content

Commit

Permalink
fix(core): preselect first state when country is selected (#722)
Browse files Browse the repository at this point in the history
* fix(core): preselect first state when country is selected

* refactor: white spac and state update
  • Loading branch information
jorgemoya committed Apr 3, 2024
1 parent 5cbf0ab commit b3cddde
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 19 deletions.
5 changes: 5 additions & 0 deletions .changeset/mean-meals-appear.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@bigcommerce/catalyst-core": patch
---

Preselect first state when country is selected for Shipping Info
27 changes: 11 additions & 16 deletions apps/core/app/[locale]/(default)/cart/_components/shipping-info.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,7 @@ export const ShippingInfo = ({
},
);

// Fetch states when country changes
useEffect(() => {
if (formValues.country) {
const countryId = formValues.country.split('-')[1];
Expand All @@ -106,6 +107,13 @@ export const ShippingInfo = ({
}
}, [formValues.country, t]);

// Preselect first state when states array changes and state is empty
useEffect(() => {
if (formValues.states && !formValues.state) {
setFormValues({ state: formValues.states[0]?.state || '' });
}
}, [formValues.state, formValues.states]);

const onSubmit = async (formData: FormData) => {
const { status } = await submitShippingInfo(formData, {
checkoutId: checkout.entityId,
Expand All @@ -124,19 +132,6 @@ export const ShippingInfo = ({
}
};

const resetFormFieldsOnCountryChange = () => {
if (formValues.country) {
setFormValues({
states: [],
state: '',
city: '',
postcode: '',
});

hideShippingOptions();
}
};

return (
<Form
action={onSubmit}
Expand All @@ -152,12 +147,12 @@ export const ShippingInfo = ({
const countryId = value.split('-')[1];

if (countryId) {
setFormValues({ country: value });
setFormValues({ country: value, states: [], state: '', city: '', postcode: '' });
} else {
setFormValues({ country: '' });
setFormValues({ country: '', states: [], state: '', city: '', postcode: '' });
}

resetFormFieldsOnCountryChange();
hideShippingOptions();
}}
placeholder={t('countryPlaceholder')}
value={formValues.country}
Expand Down
4 changes: 1 addition & 3 deletions packages/components/src/components/form/form.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -68,9 +68,7 @@ const FieldLabel = forwardRef<ElementRef<typeof Label>, FieldLabelProps>(
{...props}
>
<span>{children}</span>
{isRequired && (
<span className="text-xs font-normal font-normal text-gray-500">Required</span>
)}
{isRequired && <span className="text-xs font-normal text-gray-500">Required</span>}
</Label>
),
);
Expand Down

0 comments on commit b3cddde

Please sign in to comment.