My implementation involves using the remote data feature of Select2 (version 4.0.6-rc.1) to fetch results from a Swagger API endpoint. Despite limited documentation on server-side data loading, I managed to work around the issue at hand. However, there seems to be a problem where the dropdown fails to display the most recent param.term
result.
My approach mainly focuses on Aurelia-specific functionalities when referring to the <select>
element.
In my HTML:
<select class="select2" ref="referenceToHTMLSelect2"></select>
Here is the code snippet:
optionsInSelect2Format = { text: string, id: string }[];
theSelect2: any;
variableId: string;
variableName: string;
public initializeSelect2() {
this.theSelect2 = $(this.referenceToHTMLSelect2).select2({
placeholder: 'Select',
width: '100%',
minimumInputLength: 1,
language: {
inputTooShort: () => {
return 'Enter at least 1 character to search'
}
},
ajax: {
url: (params) => {
this.apiCall(params.term, "hardCodedStringNeededToExecuteAPICall");
},
processResults: (params) => {
return {
results: this.optionsInSelect2Format
}
}
}
});
this.theSelect2.on('select2:select', (e) => {
let data = this.theSelect2.select2('data')[0];
this.variableId = data.id;
this.variableName = data.text;
});
}
Regarding the API call:
public apiCall(searchTerm: string, type: string) {
return this.service.search(seachTerm, type)
.then(response => {
if (response.status === 200) {
const rawJSON = response.result;
this.optionsInSelect2Format = [];
//Lodash ForEach
_.forEach(rawJSON, (entry) => {
this.optionsInSelect2Format.push({
text: entry.entryName,
id: entry.entryID
});
});
return this.optionsInSelect2Format;
}
}
})
.catch(error => {
//Error message
});
The issue arises as the API call triggers upon user keystrokes, but the dropdown refresh does not consistently occur. It appears that the dropdown reloads only after typing the first or second characters, lagging behind the actual param.term entered. For instance, if a user types "i," the results fail to load, and subsequent typing of "t" loads the initial "i" results instead of the expected "it" results into the dropdown.
Although the optionsInSelect2Format
array updates correctly with "it" results, could this be an asynchronous problem?
For reference, here's a GIF illustrating the behavior: