Skip to content

Commit

Permalink
make fetch cancellable, close #65
Browse files Browse the repository at this point in the history
  • Loading branch information
mskocik committed Dec 9, 2021
1 parent b117313 commit 129c535
Showing 1 changed file with 16 additions and 8 deletions.
24 changes: 16 additions & 8 deletions src/Svelecte.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -157,9 +157,12 @@
/** ************************************ remote source */
// $: initFetchOnly = fetchMode === 'init' || (typeof fetch === 'string' && fetch.indexOf('[query]') === -1);
$: createFetch(fetch);
$: {
if (disabled) {
xhr && xhr.readyState !== 4 && xhr.abort();
$: disabled && cancelXhr();
function cancelXhr() {
if (isFetchingData) {
xhr && ![0,4].includes(xhr.readyState) && xhr.abort();
isFetchingData = false;
}
}
Expand All @@ -173,11 +176,17 @@
const fetchSource = typeof fetch === 'string' ? fetchRemote(fetch) : fetch;
initFetchOnly = fetchMode === 'init' || (fetchMode === 'auto' && typeof fetch === 'string' && fetch.indexOf('[query]') === -1);
const debouncedFetch = debounce(query => {
if (query && !$inputValue.length) {
isFetchingData = false;
return;
}
fetchSource(query, fetchCallback)
.then(data => {
options = data;
})
.catch(() => options = [])
.catch(() => {
options = []
})
.finally(() => {
isFetchingData = false;
$hasFocus && hasDropdownOpened.set(true);
Expand All @@ -194,18 +203,16 @@
}
fetchUnsubscribe = inputValue.subscribe(value => {
if (xhr && xhr.readyState !== 4) { // cancel previously run
xhr.abort();
};
cancelXhr(); // cancel previous run
if (!value) {
if (isInitialized && fetchResetOnBlur) {
options = [];
}
return;
}
if (value && value.length < minQuery) return;
isFetchingData = true;
!initFetchOnly && hasDropdownOpened.set(false);
isFetchingData = true;
debouncedFetch(value);
});
Expand Down Expand Up @@ -508,6 +515,7 @@
if (!$inputValue) {
$hasDropdownOpened = false;
}
cancelXhr();
$inputValue = '';
break;
case Tab:
Expand Down

0 comments on commit 129c535

Please sign in to comment.