Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions src/helpers/debounce.ts
Original file line number Diff line number Diff line change
@@ -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)
}
}
13 changes: 13 additions & 0 deletions src/lib/core.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -303,6 +304,12 @@ export default class Core<T> extends PureComponent<Props<T>, IState<T>> {
}
}

private debouncedFormChange = debounce(newState => {
if (!this.props.onFormChange) return;

this.props.onFormChange(newState)
},this.props.delayToDebounceChange ?? 500)

onFieldsChange(field: Field<any>, val: any, doOnChange: boolean) {
const { validationForm, usedFields, fieldsState } = this.state

Expand Down Expand Up @@ -338,6 +345,10 @@ export default class Core<T> extends PureComponent<Props<T>, IState<T>> {
})

if (doOnChange && this.props.onFormChange) {
if (!this.props.executeChangeOnBlur && this.props.executeDebounceChange) {
this.debouncedFormChange(newState)
return;
}
this.props.onFormChange(newState)
}
}
Expand Down Expand Up @@ -418,6 +429,8 @@ Core.defaultProps = {
fields: [],
onFormChange: () => {},
executeChangeOnBlur: true,
executeDebounceChange: false,
delayToDebounceChange: 500,
defaultState: {},
parseState: () => {},
showValidation: false,
Expand Down
2 changes: 2 additions & 0 deletions src/types/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,8 @@ export interface Props<T> {
defaultState?: T
parseState?: Function
executeChangeOnBlur?: boolean
executeDebounceChange?: boolean
delayToDebounceChange?: number
}

export interface FormComponent {
Expand Down
27 changes: 27 additions & 0 deletions stories/1-Basic.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -262,6 +262,33 @@ export const WithRef = () => {
)
}

export const WithDebounceChange = () => (
<DForm
executeChangeOnBlur={false}
executeDebounceChange
onFormChange={() => 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 = () => <Button onClick={action('clicked')}>Hello Button</Button>;

// export const Emoji = () => (
Expand Down