Skip to content

Commit

Permalink
add debounce
Browse files Browse the repository at this point in the history
prevent frequent api calls when changing item names
  • Loading branch information
mxkae committed Nov 6, 2024
1 parent e9275d6 commit b53b3ff
Showing 1 changed file with 31 additions and 7 deletions.
38 changes: 31 additions & 7 deletions src/components/sortable-picker/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ import {
Dashicon,
Dropdown,
} from '@wordpress/components'
import { useState } from '@wordpress/element'
import { useState, useEffect } from '@wordpress/element'
import { __ } from '@wordpress/i18n'

const addItemPopoverProps = {
Expand Down Expand Up @@ -138,11 +138,31 @@ const LabeledItemIndicator = props => {
onChange,
ItemPreview = null,
ItemPicker = null,

enableDebounce = true, // If false, onChange will be called immediately.
} = props

const [ isFocused, setIsFocused ] = useState( false )

const [ debouncedText, setDebouncedText ] = useState( item.name )

useEffect( () => {
setDebouncedText( item.name )
}, [ item.name ] )

useEffect( () => {
let timeout
if ( item.name !== debouncedText && enableDebounce ) {
timeout = setTimeout( () => {
onChange( {
...item,
name: debouncedText,
} )
}, 300 )
}

return () => clearTimeout( timeout )
}, [ debouncedText, onChange ] )

return (
<HStack justify="space-between" className="stk-global-settings-color-picker__color-indicator-wrapper">
<Dropdown
Expand All @@ -164,12 +184,16 @@ const LabeledItemIndicator = props => {
<ItemPreview item={ item } />
<input
className="components-input-control__input"
value={ item.name }
value={ debouncedText }
onChange={ ev => {
onChange( {
...item,
name: ev.target.value,
} )
if ( enableDebounce ) {
setDebouncedText( ev.target.value )
} else {
onChange( {
...item,
name: ev.target.value,
} )
}
} }
onFocus={ () => setIsFocused( true ) }
onBlur={ ev => {
Expand Down

0 comments on commit b53b3ff

Please sign in to comment.