Skip to content

Commit

Permalink
feat: add debounceDelay option for onChange
Browse files Browse the repository at this point in the history
  • Loading branch information
Rob Dekker committed Sep 29, 2023
1 parent 40d3e39 commit 8fea131
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 3 deletions.
18 changes: 17 additions & 1 deletion src/components/textinput.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@
validationAboveMaximum = [''],
value,
hideLabel,
debounceDelay,
dataComponentAttribute = ['TextField'],
required,
} = options;
Expand Down Expand Up @@ -64,6 +65,7 @@
const [currentValue, setCurrentValue] = usePageState(useText(value));
const parsedLabel = useText(label);
const labelText = parsedLabel;
const debouncedOnChangeRef = useRef(null);

const validPattern = pattern || null;
const validMinlength = minLength || null;
Expand Down Expand Up @@ -140,6 +142,20 @@
};
};

const debounce =
(func, delay) =>
(...args) => {
clearTimeout(debounce.timeoutId);
debounce.timeoutId = setTimeout(() => func(...args), delay);
};
debounce.timeoutId = null;

if (!debouncedOnChangeRef.current) {
debouncedOnChangeRef.current = debounce((newValue) => {
B.triggerEvent('onChange', newValue);
}, debounceDelay);
}

const changeHandler = (event) => {
const { target } = event;
let { validity: validation } = target;
Expand All @@ -156,7 +172,7 @@
}
const newValue = isNumberType ? numberValue : eventValue;
setCurrentValue(newValue);
B.triggerEvent('onChange', newValue);
debouncedOnChangeRef.current(newValue);
};

const blurHandler = (event) => {
Expand Down
2 changes: 1 addition & 1 deletion src/prefabs/structures/TextInput/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ export const TextInput = (
{
label: 'Advanced Options',
expanded: false,
members: ['dataComponentAttribute'],
members: ['debounceDelay', 'dataComponentAttribute'],
},
];

Expand Down
3 changes: 2 additions & 1 deletion src/prefabs/structures/TextInput/options/advanced.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { variable } from '@betty-blocks/component-sdk';
import { number, variable } from '@betty-blocks/component-sdk';

export const advanced = {
debounceDelay: number('Debounce delay (in ms)'),
dataComponentAttribute: variable('Test attribute', {
value: [],
}),
Expand Down

0 comments on commit 8fea131

Please sign in to comment.