Rework dropdown changes (#1964)
This commit is contained in:
parent
1f7d31c0ef
commit
c0401aefe3
@ -4,7 +4,7 @@
|
||||
|
||||
import { BareProps } from './types';
|
||||
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import React, { useEffect, useRef, useState } from 'react';
|
||||
import styled from 'styled-components';
|
||||
import SUIButton from 'semantic-ui-react/dist/commonjs/elements/Button/Button';
|
||||
import SUIDropdown, { DropdownProps } from 'semantic-ui-react/dist/commonjs/modules/Dropdown/Dropdown';
|
||||
@ -40,31 +40,33 @@ interface Props<Option> extends BareProps {
|
||||
}
|
||||
|
||||
function Dropdown<Option> ({ allowAdd = false, className, defaultValue, dropdownClassName, help, isButton, isDisabled, isError, isMultiple, label, labelExtra, onAdd, onBlur, onChange, onClose, onSearch, options, placeholder, renderLabel, searchInput, style, transform, withEllipsis, withLabel, value }: Props<Option>): React.ReactElement<Props<Option>> {
|
||||
const [stateValue, setStateValue] = useState<any>();
|
||||
const lastUpdate = useRef<string>('');
|
||||
const [stored, setStored] = useState<any>();
|
||||
|
||||
const _setStored = (value: any): void => {
|
||||
const json = JSON.stringify({ v: value });
|
||||
|
||||
if (lastUpdate.current !== json) {
|
||||
lastUpdate.current = json;
|
||||
|
||||
setStored(value);
|
||||
onChange && onChange(
|
||||
transform
|
||||
? transform(value)
|
||||
: value
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect((): void => {
|
||||
_setStored(isUndefined(value) ? defaultValue : value);
|
||||
}, [defaultValue, value]);
|
||||
|
||||
const _onAdd = (_: React.SyntheticEvent<HTMLElement>, { value }: DropdownProps): void =>
|
||||
onAdd && onAdd(value);
|
||||
|
||||
const _onChange = (_: React.SyntheticEvent<HTMLElement> | null, { value }: DropdownProps): void => {
|
||||
setStateValue(value);
|
||||
|
||||
onChange && onChange(
|
||||
transform
|
||||
? transform(value)
|
||||
: value
|
||||
);
|
||||
};
|
||||
|
||||
useEffect((): void => {
|
||||
const newValue = isUndefined(value)
|
||||
? defaultValue
|
||||
: value;
|
||||
|
||||
// only update parent if we have had something changed
|
||||
if (JSON.stringify({ v: newValue }) !== JSON.stringify({ v: stateValue })) {
|
||||
_onChange(null, { value: newValue });
|
||||
}
|
||||
}, [defaultValue, stateValue, value]);
|
||||
const _onChange = (_: React.SyntheticEvent<HTMLElement> | null, { value }: DropdownProps): void =>
|
||||
_setStored(value);
|
||||
|
||||
const dropdown = (
|
||||
<SUIDropdown
|
||||
@ -86,7 +88,7 @@ function Dropdown<Option> ({ allowAdd = false, className, defaultValue, dropdown
|
||||
search={onSearch || allowAdd}
|
||||
searchInput={searchInput}
|
||||
selection
|
||||
value={stateValue}
|
||||
value={stored}
|
||||
/>
|
||||
);
|
||||
|
||||
|
||||
Loading…
Reference in New Issue
Block a user