From 04bd4b4566403d3fd2f16c045f5e581ea6b0e3d6 Mon Sep 17 00:00:00 2001 From: Thomas Roberts Date: Wed, 27 Jul 2022 14:04:53 +0100 Subject: [PATCH] Ensure addresses sync when loading the checkout shipping address block --- .../checkout-shipping-address-block/block.tsx | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/assets/js/blocks/checkout/inner-blocks/checkout-shipping-address-block/block.tsx b/assets/js/blocks/checkout/inner-blocks/checkout-shipping-address-block/block.tsx index e27c479e64c..eb7a5062bd5 100644 --- a/assets/js/blocks/checkout/inner-blocks/checkout-shipping-address-block/block.tsx +++ b/assets/js/blocks/checkout/inner-blocks/checkout-shipping-address-block/block.tsx @@ -2,7 +2,7 @@ * External dependencies */ import { __ } from '@wordpress/i18n'; -import { useMemo, useEffect, Fragment } from '@wordpress/element'; +import { useMemo, useEffect, Fragment, useState } from '@wordpress/element'; import { AddressForm } from '@woocommerce/base-components/cart-checkout'; import { useCheckoutAddress, @@ -48,6 +48,10 @@ const Block = ( { const { dispatchCheckoutEvent } = useStoreEvents(); const { isEditor } = useEditorContext(); + // This is used to track whether the "Use shipping as billing" checkbox was checked on first load and if we synced + // the shipping address to the billing address if it was. This is not used on further toggles of the checkbox. + const [ addressesSynced, setAddressesSynced ] = useState( false ); + // Clears data if fields are hidden. useEffect( () => { if ( ! showPhoneField ) { @@ -55,6 +59,18 @@ const Block = ( { } }, [ showPhoneField, setShippingPhone ] ); + // Run this on first render to ensure addresses sync if needed, there is no need to re-run this when toggling the + // checkbox. + useEffect( () => { + if ( addressesSynced ) { + return; + } + if ( useShippingAsBilling ) { + setBillingAddress( shippingAddress ); + } + setAddressesSynced( true ); + }, [ setBillingAddress, shippingAddress, useShippingAsBilling ] ); + const addressFieldsConfig = useMemo( () => { return { company: {