diff --git a/packages/ui/src/components/InputFields/SmartInputField/use-smart-input-field.ts b/packages/ui/src/components/InputFields/SmartInputField/use-smart-input-field.ts index d0ca52169..ff499bfc5 100644 --- a/packages/ui/src/components/InputFields/SmartInputField/use-smart-input-field.ts +++ b/packages/ui/src/components/InputFields/SmartInputField/use-smart-input-field.ts @@ -3,6 +3,7 @@ import { assert } from '@silverhand/essentials'; import { useState, useCallback, useMemo } from 'react'; import type { ChangeEventHandler } from 'react'; +import useUpdateEffect from '@/hooks/use-update-effect'; import { getDefaultCountryCallingCode } from '@/utils/country-code'; import { parseIdentifierValue } from '@/utils/form'; @@ -121,6 +122,12 @@ const useSmartInputField = ({ _defaultType, defaultValue, enabledTypes }: Props) setCurrentType(enabledTypeSet.size === 1 ? defaultType : undefined); }, [defaultType, enabledTypeSet.size]); + // CAUTION: For preview use only, enabledTypes and defaultType should not be changed after component mounted + useUpdateEffect(() => { + setInputValue(''); + setCurrentType(defaultType); + }, [defaultType]); + return { countryCode, onCountryCodeChange, diff --git a/packages/ui/src/hooks/use-update-effect.ts b/packages/ui/src/hooks/use-update-effect.ts new file mode 100644 index 000000000..dc8c864b3 --- /dev/null +++ b/packages/ui/src/hooks/use-update-effect.ts @@ -0,0 +1,19 @@ +import type { DependencyList, EffectCallback } from 'react'; +import { useEffect, useRef } from 'react'; + +const useUpdateEffect = (effect: EffectCallback, dependencies: DependencyList | undefined = []) => { + const isMounted = useRef(false); + + useEffect(() => { + if (!isMounted.current) { + // eslint-disable-next-line @silverhand/fp/no-mutation + isMounted.current = true; + + return; + } + + return effect(); + }, [...dependencies]); +}; + +export default useUpdateEffect;