Skip to content

Commit

Permalink
Fetch data source only when component is mounted
Browse files Browse the repository at this point in the history
This way, data for components that are hidden at first (for example in
inactive tabs) won't be fetched until required. We then save a bunch of
requests to the server, when navigating from one page to another,
without opening tabs.

On date range refresh, however, the data sources will be requested
again even if the component using the data is not visible anymore.
  • Loading branch information
pgiraud committed Feb 7, 2025
1 parent fbcfe40 commit 3c5fe5c
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 15 deletions.
7 changes: 6 additions & 1 deletion powa/static/js/composables/DataLoaderService.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,12 @@ export function useDataLoader(metric) {
const { dataSources } = storeToRefs(useDashboardStore());
const source = computed(() => dataSources.value[metric]);
const loading = computed(() => source.value.isFetching);
const data = computed(() => source.value.data);
const data = computed(() => {
if (!source.value.executed) {
source.value.execute();
}
return source.value.data;
});

return { data, loading, source };
}
35 changes: 21 additions & 14 deletions powa/static/js/stores/dashboard.js
Original file line number Diff line number Diff line change
Expand Up @@ -73,12 +73,32 @@ export const useDashboardStore = defineStore("dashboard", () => {
);
}

function executeFn() {
source.isFetching = true;
source.controller = new AbortController();
fetch(`${source.config.data_url}?${urlSearchParams.value}`, {
signal: source.controller.signal,
})
.then((res) => res.json())
.then((json) => {
source.data = json;
addAlertMessages(json.messages);
})
.catch((err) => (source.error = err))
.finally(() => {
source.isFetching = false;
});
source.executed = true;
}

const source = reactive({
config,
isFetching: true,
data: null,
error: null,
controller: null,
executed: false,
execute: executeFn,
});
dataSources.value[config.name] = source;
});
Expand All @@ -91,20 +111,7 @@ export const useDashboardStore = defineStore("dashboard", () => {
function fetchDataSources() {
cleanUpDataSources();
_.each(dataSources.value, (source) => {
source.isFetching = true;
source.controller = new AbortController();
fetch(`${source.config.data_url}?${urlSearchParams.value}`, {
signal: source.controller.signal,
})
.then((res) => res.json())
.then((json) => {
source.data = json;
addAlertMessages(json.messages);
})
.catch((err) => (source.error = err))
.finally(() => {
source.isFetching = false;
});
source.executed && source.execute();
});
}

Expand Down

0 comments on commit 3c5fe5c

Please sign in to comment.