Skip to content

Commit

Permalink
fix: ui.text_field value not changing with use_state (#498)
Browse files Browse the repository at this point in the history
Resolves #372

**Changes Implemented:**
- Added a `useEffect` that updates the local `value` state in the
`TextField` whenever the `propValue` changes, which is the value that
would be changed using the `use_state`
  • Loading branch information
AkshatJawne committed Jun 3, 2024
1 parent c735dec commit 7d41072
Showing 1 changed file with 37 additions and 5 deletions.
42 changes: 37 additions & 5 deletions plugins/ui/src/js/src/elements/spectrum/TextField.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,20 @@ import {
TextField as DHCTextField,
TextFieldProps as DHCTextFieldProps,
} from '@deephaven/components';
import { useDebouncedCallback } from '@deephaven/react-hooks';
import Log from '@deephaven/log';
import { useDebouncedCallback, usePrevious } from '@deephaven/react-hooks';

const log = Log.module('@deephaven/js-plugin-ui/TextField');

const VALUE_CHANGE_DEBOUNCE = 250;

const EMPTY_FUNCTION = () => undefined;

function TextField(props: DHCTextFieldProps): JSX.Element {
interface TextFieldProps extends DHCTextFieldProps {
onChange?: (value: string) => Promise<void>;
}

function TextField(props: TextFieldProps): JSX.Element {
const {
defaultValue = '',
value: propValue,
Expand All @@ -18,16 +25,41 @@ function TextField(props: DHCTextFieldProps): JSX.Element {
} = props;

const [value, setValue] = useState(propValue ?? defaultValue);
const [pending, setPending] = useState(false);
const prevPropValue = usePrevious(propValue);

// Update local value to new propValue if the server sent a new propValue and no user changes have been queued
if (
propValue !== prevPropValue &&
propValue !== value &&
propValue !== undefined &&
!pending
) {
setValue(propValue);
}

const propDebouncedOnChange = useCallback(
async (newValue: string) => {
try {
await propOnChange(newValue);
} catch (e) {
log.warn('Error returned from onChange', e);
}
setPending(false);
},
[propOnChange]
);

const debouncedOnChange = useDebouncedCallback(
propOnChange,
propDebouncedOnChange,
VALUE_CHANGE_DEBOUNCE
);

const onChange = useCallback(
newValue => {
setValue(newValue);
(newValue: string) => {
setPending(true);
debouncedOnChange(newValue);
setValue(newValue);
},
[debouncedOnChange]
);
Expand Down

0 comments on commit 7d41072

Please sign in to comment.