hooks_use-phone-input-format-utils.js

import { React } from '@gravityforms/libraries';

const { useEffect, useRef, useState } = React;

/**
 * @function usePhoneInputFormatUtils
 * @description Custom hook to access the phone input format utils.
 *
 * @since 1.0.0
 *
 * @param {object}   args         The arguments.
 * @param {Function} args.onError The function to call when an error occurs.
 *
 * @return {object} The return value of the hook.
 */
const usePhoneInputFormatUtils = ( {
	onError,
} = {} ) => {
	const [ inputFormatUtils, setInputFormatUtils ] = useState( null );
	const [ isLoading, setIsLoading ] = useState( true );
	const onErrorRef = useRef( onError );
	onErrorRef.current = onError;

	useEffect( () => {
		const inputFormatUtilsPromise = import( '@gravityforms/components/react/admin/modules/Phone/input-format-utils' );
		inputFormatUtilsPromise
			.then( ( module ) => {
				setInputFormatUtils( module );
			} )
			.catch( ( error ) => {
				onErrorRef.current?.( error );
			} )
			.finally( () => {
				setIsLoading( false );
			} );
	}, [] );

	return {
		inputFormatUtils,
		isLoading,
	};
};

export default usePhoneInputFormatUtils;