diff --git a/src/helpers/debounce.ts b/src/helpers/debounce.ts new file mode 100644 index 0000000..e4ad00d --- /dev/null +++ b/src/helpers/debounce.ts @@ -0,0 +1,7 @@ +export function debounce(callback: (...args: any) => void, delay: number) { + let timer: number; + return (...args: any) => { + clearTimeout(timer); + timer = setTimeout(() => callback(...args), delay) + } +} diff --git a/src/lib/core.tsx b/src/lib/core.tsx index eb3ecd5..ccb249c 100644 --- a/src/lib/core.tsx +++ b/src/lib/core.tsx @@ -4,6 +4,7 @@ import regex from './regex' import { get as get_ } from 'lodash' import { hasKey } from '../helpers/hasKey' +import { debounce } from '../helpers/debounce' export type Tvalidation = { isValid: boolean @@ -303,6 +304,12 @@ export default class Core extends PureComponent, IState> { } } + private debouncedFormChange = debounce(newState => { + if (!this.props.onFormChange) return; + + this.props.onFormChange(newState) + },this.props.delayToDebounceChange ?? 500) + onFieldsChange(field: Field, val: any, doOnChange: boolean) { const { validationForm, usedFields, fieldsState } = this.state @@ -338,6 +345,10 @@ export default class Core extends PureComponent, IState> { }) if (doOnChange && this.props.onFormChange) { + if (!this.props.executeChangeOnBlur && this.props.executeDebounceChange) { + this.debouncedFormChange(newState) + return; + } this.props.onFormChange(newState) } } @@ -418,6 +429,8 @@ Core.defaultProps = { fields: [], onFormChange: () => {}, executeChangeOnBlur: true, + executeDebounceChange: false, + delayToDebounceChange: 500, defaultState: {}, parseState: () => {}, showValidation: false, diff --git a/src/types/index.ts b/src/types/index.ts index b1c35c4..c8e2b63 100644 --- a/src/types/index.ts +++ b/src/types/index.ts @@ -61,6 +61,8 @@ export interface Props { defaultState?: T parseState?: Function executeChangeOnBlur?: boolean + executeDebounceChange?: boolean + delayToDebounceChange?: number } export interface FormComponent { diff --git a/stories/1-Basic.stories.tsx b/stories/1-Basic.stories.tsx index a71a5c4..3e69dd9 100644 --- a/stories/1-Basic.stories.tsx +++ b/stories/1-Basic.stories.tsx @@ -262,6 +262,33 @@ export const WithRef = () => { ) } +export const WithDebounceChange = () => ( + console.log("executeDebounceChange")} + fields={[ + { + fields: [ + { + name: "name", + placeholder: "Name", + type: "Input", + props: { + onKeyPress: (e) => { + if (e.which == 32) { + e.preventDefault(); + console.log("Space Detected"); + return false; + } + }, + }, + }, + ], + }, + ]} + /> +) // export const Text = () => ; // export const Emoji = () => (