Correctly detect selected location on first mount

This commit is contained in:
Mike Jolley 2023-01-12 12:19:19 +00:00 committed by Nadir Seghir
parent 5076541597
commit 7196a76577
1 changed files with 10 additions and 6 deletions

View File

@ -108,7 +108,16 @@ const renderPickupLocation = (
const Block = (): JSX.Element | null => {
const { shippingRates, selectShippingRate } = useShippingData();
const [ selectedOption, setSelectedOption ] = useState< string >( '' );
// Get pickup locations from the first shipping package.
const pickupLocations = ( shippingRates[ 0 ]?.shipping_rates || [] ).filter(
( { method_id: methodId } ) => methodId === 'pickup_location'
);
const [ selectedOption, setSelectedOption ] = useState< string >(
() => pickupLocations.find( ( rate ) => rate.selected )?.rate_id || ''
);
const onSelectRate = useCallback(
( rateId: string ) => {
selectShippingRate( rateId );
@ -116,11 +125,6 @@ const Block = (): JSX.Element | null => {
[ selectShippingRate ]
);
// Get pickup locations from the first shipping package.
const pickupLocations = ( shippingRates[ 0 ]?.shipping_rates || [] ).filter(
( { method_id: methodId } ) => methodId === 'pickup_location'
);
// Update the selected option if there is no rate selected on mount.
useEffect( () => {
if ( ! selectedOption && pickupLocations[ 0 ] ) {