From 8f5dbd5ccaf0a418ec5e7a0a832233121efe61c3 Mon Sep 17 00:00:00 2001 From: Robert Anderson Date: Wed, 28 Oct 2020 15:40:15 +1100 Subject: [PATCH] URLInput: Use debounce() instead of throttle() Wait until the user finishes typing before sending an AJAX request. This ensures that there isn't an AJAX request sent every 200 ms while the user is typing. --- .../src/components/link-control/test/index.js | 8 +++++++- packages/block-editor/src/components/url-input/index.js | 4 ++-- 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/packages/block-editor/src/components/link-control/test/index.js b/packages/block-editor/src/components/link-control/test/index.js index 344da8f08d29c4..2c1efc9352bdd0 100644 --- a/packages/block-editor/src/components/link-control/test/index.js +++ b/packages/block-editor/src/components/link-control/test/index.js @@ -4,7 +4,7 @@ import { render, unmountComponentAtNode } from 'react-dom'; import { act, Simulate } from 'react-dom/test-utils'; import { queryByText, queryByRole } from '@testing-library/react'; -import { first, last, nth, uniqueId } from 'lodash'; +import { default as lodash, first, last, nth, uniqueId } from 'lodash'; /** * WordPress dependencies */ @@ -16,6 +16,12 @@ import { UP, DOWN, ENTER } from '@wordpress/keycodes'; import LinkControl from '../'; import { fauxEntitySuggestions, fetchFauxEntitySuggestions } from './fixtures'; +// Mock debounce() so that it runs instantly. +lodash.debounce = jest.fn( ( callback ) => { + callback.cancel = jest.fn(); + return callback; +} ); + const mockFetchSearchSuggestions = jest.fn(); jest.mock( '@wordpress/data/src/components/use-select', () => () => ( { diff --git a/packages/block-editor/src/components/url-input/index.js b/packages/block-editor/src/components/url-input/index.js index 5d1876960eeffe..26b0f98c81daf2 100644 --- a/packages/block-editor/src/components/url-input/index.js +++ b/packages/block-editor/src/components/url-input/index.js @@ -1,7 +1,7 @@ /** * External dependencies */ -import { throttle, isFunction } from 'lodash'; +import { debounce, isFunction } from 'lodash'; import classnames from 'classnames'; import scrollIntoView from 'dom-scroll-into-view'; @@ -40,7 +40,7 @@ class URLInput extends Component { this.bindSuggestionNode = this.bindSuggestionNode.bind( this ); this.autocompleteRef = props.autocompleteRef || createRef(); this.inputRef = createRef(); - this.updateSuggestions = throttle( + this.updateSuggestions = debounce( this.updateSuggestions.bind( this ), 200 );