import { onMounted, onUnmounted, ref } from 'vue'; import { useRouter, useRoute } from 'vue-router'; import axios from 'axios'; import { useArrayDataStore } from 'stores/useArrayDataStore'; const arrayDataStore = useArrayDataStore(); export function useArrayData(key, userOptions) { if (!key) throw new Error('ArrayData: A key is required to use this composable'); if (!arrayDataStore.get(key)) { arrayDataStore.set(key); } const store = arrayDataStore.get(key); const hasMoreData = ref(false); const router = useRouter(); const route = useRoute(); const page = ref(1); if (typeof userOptions === 'object') { if (userOptions.filter) store.filter = userOptions.filter; if (userOptions.url) store.url = userOptions.url; if (userOptions.limit) store.limit = userOptions.limit; if (userOptions.order) store.order = userOptions.order; //Object.assign(store.value, userOptions); //console.log(options.value); } // if (typeof userOptions === 'object' && userOptions.filter) { // Object.assign(filter.value, userOptions.filter); // } onMounted(() => { const query = route.query; if (query.params) { store.userParams = JSON.parse(query.params); } }); onUnmounted(() => { // if (arrayDataStore.get(key)) { // arrayDataStore.clear(key); // } // do stuff }); async function fetch({ append = false }) { if (!store.url) return; const filter = { order: store.order, limit: store.limit, skip: store.skip, }; Object.assign(filter, store.userFilter); Object.assign(filter, store.filter); store.filter = filter; const params = { filter: JSON.stringify(filter), }; Object.assign(params, store.userParams); const response = await axios.get(store.url, { params }); const { limit } = filter; hasMoreData.value = response.data.length === limit; if (append === true) { for (const row of response.data) store.data.push(row); } if (append === false) { store.data = response.data; updateStateParams(); } } async function request({ userFilter }) { if (!store.url) return; const filter = { order: store.order, limit: store.limit, skip: store.skip, }; Object.assign(filter, userFilter); const requestOptions = { params: { filter: filter } }; const response = await axios.get(store.url, requestOptions); return response.data; } async function apply({ filter, params }) { if (filter) store.userFilter = filter; if (params) store.userParams = Object.assign({}, params); await fetch({ append: false }); } async function loadMore() { if (!hasMoreData.value) return; store.skip = store.limit * (page.value - 1); page.value += 1; await fetch({ append: true }); } async function refresh() { // TODO: Refresh } function updateStateParams() { router.replace({ path: route.path, query: { order: store.order, limit: store.limit, skip: store.skip, params: JSON.stringify(store.userParams), }, }); } return { fetch, apply, refresh, request, loadMore, store, hasMoreData, updateStateParams, }; }