diff --git a/src/store/subscriptions.js b/src/store/subscriptions.js index 4c8ad43..f4ed67c 100644 --- a/src/store/subscriptions.js +++ b/src/store/subscriptions.js @@ -1,47 +1,55 @@ import { capitalize } from "./utils.js"; export default function subscribeActions(store, pageDefinition) { - store.$onAction(({ name, store, args, after }) => { - //before action is called - runSubscriptions(name, args, store, pageDefinition, "before"); - after(() => { - runSubscriptions(name, args, store, pageDefinition, "after"); + store.$onAction(async ({ name, store, args, after }) => { + // issues with this approach: + // using await here causes the after() callback not to run + // also, the action itself does not wait for runSubscriptions to finish ie beforeSet is not completing before setting the filter + await runSubscriptions(name, args, store, pageDefinition, "before"); + after(async () => { + await runSubscriptions(name, args, store, pageDefinition, "after"); }); }); } -function runSubscriptions(name, args, store, pageDefinition, hook) { +async function runSubscriptions(name, args, store, pageDefinition, hook) { // for loadData actions, both toggle the dataLoading state variable // and also check for before/after loadData hooks if (name === "loadData") { store.toggleDataLoading(); if (pageDefinition[`${hook}LoadData`]) { - pageDefinition[`${hook}LoadData`]({ name, args }, store); + await pageDefinition[`${hook}LoadData`]({ name, args }, store); } } else if (name.includes("Filter") && name !== "setFilter") { // iterate over filters to find if any match the action name // and run their before/after hooks - Object.keys(store.getFilters).forEach((filterKey) => { + const filterKeys = Object.keys(store.getFilters); + // use for of because forEach does not work with async + for (const filterKey of filterKeys) { const filterActionString = `set${capitalize(filterKey)}Filter`; if ( name === filterActionString && store.getFilters[filterKey][`${hook}Set`] ) { - store.getFilters[filterKey][`${hook}Set`]({ name, args }, store); + await store.getFilters[filterKey][`${hook}Set`]({ name, args }, store); + if (hook === "after" && !store.getFilters[filterKey].synchronous) { + await store.loadData(); + } } - }); + } } else if (name.includes("ChartData") && name !== "setChartData") { // iterate over hcarts to find if any match the action name // and run their before/after hooks - Object.keys(store.getCharts).forEach((chartKey) => { + const chartKeys = Object.keys(store.getCharts); + for (const chartKey of chartKeys) { const chartActionString = `set${capitalize(chartKey)}ChartData`; if ( name === chartActionString && store.getCharts[chartKey][`${hook}Set`] ) { - store.getCharts[chartKey][`${hook}Set`]({ name, args }, store); + await store.getCharts[chartKey][`${hook}Set`]({ name, args }, store); } - }); + } } if (pageDefinition.extendSubscriptions) {