2020-03-13 19:04:03 +00:00
|
|
|
/**
|
|
|
|
* External dependencies
|
|
|
|
*/
|
|
|
|
import { useDispatch } from '@wordpress/data';
|
|
|
|
import { useEffect, useState } from '@wordpress/element';
|
|
|
|
import isShallowEqual from '@wordpress/is-shallow-equal';
|
|
|
|
import { useDebounce } from 'use-debounce';
|
|
|
|
import { CART_STORE_KEY as storeKey } from '@woocommerce/block-data';
|
2020-03-24 10:28:19 +00:00
|
|
|
import { decodeEntities } from '@wordpress/html-entities';
|
2020-03-13 19:04:03 +00:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Internal dependencies
|
|
|
|
*/
|
|
|
|
import { useStoreCart } from '../cart/use-store-cart';
|
2020-03-13 20:05:45 +00:00
|
|
|
import { useThrowError } from '../use-throw-error';
|
2020-03-13 19:04:03 +00:00
|
|
|
import { pluckAddress } from '../../utils';
|
|
|
|
|
|
|
|
const shouldUpdateStore = ( oldAddress, newAddress ) =>
|
|
|
|
! isShallowEqual( pluckAddress( oldAddress ), pluckAddress( newAddress ) );
|
|
|
|
|
|
|
|
export const useShippingAddress = () => {
|
|
|
|
const { shippingAddress: initialAddress } = useStoreCart();
|
|
|
|
const [ shippingAddress, setShippingAddress ] = useState( initialAddress );
|
|
|
|
const [ debouncedShippingAddress ] = useDebounce( shippingAddress, 400 );
|
|
|
|
const { updateShippingAddress } = useDispatch( storeKey );
|
2020-03-13 20:05:45 +00:00
|
|
|
const throwError = useThrowError();
|
2020-03-13 19:04:03 +00:00
|
|
|
|
|
|
|
// Note, we're intentionally not using initialAddress as a dependency here
|
|
|
|
// so that the stale (previous) value is being used for comparison.
|
|
|
|
useEffect( () => {
|
|
|
|
if (
|
|
|
|
debouncedShippingAddress.country &&
|
|
|
|
shouldUpdateStore( initialAddress, debouncedShippingAddress )
|
|
|
|
) {
|
2020-03-13 20:05:45 +00:00
|
|
|
updateShippingAddress( debouncedShippingAddress ).catch(
|
|
|
|
( error ) => {
|
|
|
|
// error is non-recoverable so throw
|
|
|
|
throwError( error );
|
|
|
|
}
|
|
|
|
);
|
2020-03-13 19:04:03 +00:00
|
|
|
}
|
|
|
|
}, [ debouncedShippingAddress ] );
|
2020-03-24 10:28:19 +00:00
|
|
|
|
|
|
|
const decodedShippingAddress = {};
|
|
|
|
Object.keys( shippingAddress ).forEach( ( key ) => {
|
|
|
|
decodedShippingAddress[ key ] = decodeEntities(
|
|
|
|
shippingAddress[ key ]
|
|
|
|
);
|
|
|
|
} );
|
|
|
|
|
2020-03-13 19:04:03 +00:00
|
|
|
return {
|
2020-03-24 10:28:19 +00:00
|
|
|
shippingAddress: decodedShippingAddress,
|
2020-03-13 19:04:03 +00:00
|
|
|
setShippingAddress,
|
|
|
|
};
|
|
|
|
};
|