Skip to content

Commit

Permalink
fix(Dropdown): wrong validation due to async state
Browse files Browse the repository at this point in the history
  • Loading branch information
MEsteves22 authored and zettca committed Nov 27, 2023
1 parent ffe4ba1 commit 8058cf0
Showing 1 changed file with 9 additions and 1 deletion.
10 changes: 9 additions & 1 deletion packages/core/src/components/Dropdown/Dropdown.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -284,10 +284,15 @@ export const HvDropdown = forwardRef<HTMLDivElement, HvDropdownProps>(
const [selectionLabel, setSelectionLabel] = useState(
getSelectionLabel(labels, placeholder, multiSelect, values)
);

const [internalValues, setInternalValues] = useState(values);

// Hack - Keeping track of internal values for validation purposes since useState is async
const internalValuesRef = useRef(values);

useEffect(() => {
setInternalValues(values);
internalValuesRef.current = values;
}, [values]);

useEffect(() => {
Expand Down Expand Up @@ -328,7 +333,8 @@ export const HvDropdown = forwardRef<HTMLDivElement, HvDropdownProps>(
setValidationState(() => {
// this will only run if status is uncontrolled
if (required) {
const hasSelection = getSelected(internalValues).length > 0;
const hasSelection =
getSelected(internalValuesRef.current).length > 0;

if (!hasSelection) {
return "invalid";
Expand All @@ -351,6 +357,8 @@ export const HvDropdown = forwardRef<HTMLDivElement, HvDropdownProps>(

if (commitChanges) {
setInternalValues(listValues);
internalValuesRef.current = listValues;

setSelectionLabel(
getSelectionLabel(labels, placeholder, multiSelect, listValues)
);
Expand Down

0 comments on commit 8058cf0

Please sign in to comment.