From 1c5bdda02a401752051e42cfa2e49d94169402e3 Mon Sep 17 00:00:00 2001 From: simeng-li Date: Thu, 9 Mar 2023 10:17:02 +0800 Subject: [PATCH] fix(ui): reset InputField on enabledTypes change (#3319) --- .../SmartInputField/use-smart-input-field.ts | 7 +++++++ packages/ui/src/hooks/use-update-effect.ts | 19 +++++++++++++++++++ 2 files changed, 26 insertions(+) create mode 100644 packages/ui/src/hooks/use-update-effect.ts 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;