/** * External dependencies */ import { __ } from '@wordpress/i18n'; import { useEffect } from 'react'; import { useValidationContext } from '@woocommerce/base-context'; import { useShallowEqual } from '@woocommerce/base-hooks'; import PropTypes from 'prop-types'; import classnames from 'classnames'; import { withInstanceId } from '@woocommerce/base-hocs/with-instance-id'; /** * Internal dependencies */ import { ValidationInputError } from '../validation'; import Select from './index'; import './style.scss'; const ValidatedSelect = ( { className, id, value, instanceId, required, errorId, errorMessage = __( 'Please select a value.', 'woo-gutenberg-products-block' ), ...rest } ) => { const selectId = id || 'select-' + instanceId; errorId = errorId || selectId; // Prevents re-renders when value is an object, e.g. {key: "NY", name: "New York"} const currentValue = useShallowEqual( value ); const { getValidationError, setValidationErrors, clearValidationError, } = useValidationContext(); const validateSelect = () => { if ( ! required || currentValue ) { clearValidationError( errorId ); } else { setValidationErrors( { [ errorId ]: { message: errorMessage, hidden: true, }, } ); } }; useEffect( () => { validateSelect(); }, [ currentValue ] ); // Remove validation errors when unmounted. useEffect( () => { return () => { clearValidationError( errorId ); }; }, [ errorId ] ); const error = getValidationError( errorId ) || {}; return (