Skip to content

Commit

Permalink
Merge pull request #19951 from code-dot-org/debounce-school-search
Browse files Browse the repository at this point in the history
debounce school search
  • Loading branch information
Hamms committed Jan 12, 2018
2 parents 6b845b6 + ba8b9cb commit dc6cabf
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 8 deletions.
22 changes: 14 additions & 8 deletions apps/src/templates/SchoolAutocompleteDropdown.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import VirtualizedSelect from 'react-virtualized-select';
import 'react-virtualized/styles.css';
import 'react-select/dist/react-select.css';
import 'react-virtualized-select/styles.css';
import _ from 'lodash';
import i18n from "@cdo/locale";

export default class SchoolAutocompleteDropdown extends Component {
Expand All @@ -27,6 +28,17 @@ export default class SchoolAutocompleteDropdown extends Component {
label: i18n.schoolNotFound()
});

debouncedSearch = _.debounce((q) => {
const searchUrl = `/dashboardapi/v1/schoolsearch/${encodeURIComponent(q)}/40`;
return fetch(searchUrl)
.then(response => response.ok ? response.json() : [])
.then(json => {
const schools = json.map(school => this.constructSchoolOption(school));
schools.unshift(this.constructSchoolNotFoundOption());
return { options: schools };
});
}, 200);

getOptions = (q) => {
// Existing value? Construct the matching option for display.
if (q.length === 0 && this.props.value) {
Expand All @@ -44,14 +56,8 @@ export default class SchoolAutocompleteDropdown extends Component {
if (q.length < 4) {
return Promise.resolve();
}
const searchUrl = `/dashboardapi/v1/schoolsearch/${encodeURIComponent(q)}/40`;
return fetch(searchUrl)
.then(response => response.ok ? response.json() : [])
.then(json => {
const schools = json.map(school => this.constructSchoolOption(school));
schools.unshift(this.constructSchoolNotFoundOption());
return { options: schools };
});

return this.debouncedSearch(q);
};

render() {
Expand Down
12 changes: 12 additions & 0 deletions apps/test/unit/templates/SchoolAutocompleteDropdownTest.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,23 @@ import {shallow} from 'enzyme';
import {expect} from '../../util/configuredChai';
import sinon from 'sinon';
import SchoolAutocompleteDropdown from '@cdo/apps/templates/SchoolAutocompleteDropdown';
import _ from 'lodash';

describe('SchoolAutocompleteDropdown', () => {
let schoolAutocompleteDropdown;
let handleChange;
let select;
let debounceStub;

before(() => {
// stub out debounce to return the original function, so it's called immediately
debounceStub = sinon.stub(_, 'debounce').callsFake(f => f);
});

after(() => {
debounceStub.restore();
});

beforeEach(() => {
handleChange = sinon.spy();
schoolAutocompleteDropdown = shallow(
Expand Down

0 comments on commit dc6cabf

Please sign in to comment.