Skip to content

Commit

Permalink
Manage fetch concurrency
Browse files Browse the repository at this point in the history
  • Loading branch information
AlexVelezLl committed Dec 17, 2024
1 parent b7fa010 commit c786127
Showing 1 changed file with 29 additions and 2 deletions.
31 changes: 29 additions & 2 deletions kolibri/plugins/coach/assets/src/composables/useFetch.js
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,9 @@ export default function useFetch(options) {
const count = ref(null);
const loadingMore = ref(false);

// useFetch metadata to manage synchronization of fetches
const _fetchCount = ref(0);

const hasMore = computed(() => moreParams.value != null);

const _setData = (response, loadingMore) => {
Expand All @@ -80,30 +83,54 @@ export default function useFetch(options) {

const fetchData = async (...args) => {
loading.value = true;
loadingMore.value = false; // Reset loading more state
error.value = null;
_fetchCount.value += 1;
const currentFetchCount = _fetchCount.value;

// If the fetch count has changed, it means that a new fetch has been triggered
// and this fetch is no longer relevant
const newFetchHasStarted = () => currentFetchCount !== _fetchCount.value;

try {
const response = await fetchMethod(...args);
if (newFetchHasStarted()) {
return;
}
_setData(response);
} catch (err) {
if (newFetchHasStarted()) {
return;
}
error.value = err;
}

loading.value = false;
};

const fetchMore = async (...args) => {
if (!moreParams.value || !fetchMoreMethod) {
if (!moreParams.value || !fetchMoreMethod || loadingMore.value || loading.value) {
return;
}

loadingMore.value = true;
error.value = null;
const currentFetchCount = _fetchCount.value;

// If the fetch count or fetch more count has changed, it means that a new fetch has been
// triggered and this fetch is no longer relevant
const newFetchHasStarted = () => currentFetchCount !== _fetchCount.value;

try {
const response = await fetchMoreMethod(moreParams.value, ...args);
_setData(response, loadingMore.value);
if (newFetchHasStarted()) {
return;
}
_setData(response, true);
} catch (err) {
if (newFetchHasStarted()) {
return;
}
error.value = err;
}

Expand Down

0 comments on commit c786127

Please sign in to comment.