import { GET_PRODUCTS } from '~/graphql/queries/standalone/products'; import type {IProductResponse} from '~/types'; interface IProdVars { first: number, categoriesSlugs: string, attributes?: string, orderBy?: string, minPrice?: number, maxPrice?: number, productAfter?: string } export function useStore( slug: string, attributes?: string, orderBy?: string, minPrice?: number, maxPrice?: number, productAfter?: string ) { const variables = reactive({ first: 15, categoriesSlugs: slug, attributes, orderBy, minPrice, maxPrice, productAfter }); const { pending, data, error, refresh } = useAsyncQuery( GET_PRODUCTS, variables ); const products = ref([...(data.value?.products.edges ?? [])]); const pageInfo = computed(() => data.value?.products.pageInfo ?? null); const isInitialized = ref(false); watch(error, e => e && console.error('useStore products error', e)); watch( data, (newData) => { if (!newData?.products?.edges) return; const newEdges = newData.products.edges; if (!isInitialized.value || !variables.productAfter) { products.value = [...newEdges]; isInitialized.value = true; } else { products.value = [...products.value, ...newEdges]; } }, { immediate: true } ); watch( () => variables.productAfter, async (newCursor, oldCursor) => { if (!newCursor || newCursor === oldCursor || !isInitialized.value) return; await refresh(); } ); watch( [ () => variables.categoriesSlugs, () => variables.attributes, () => variables.orderBy, () => variables.minPrice, () => variables.maxPrice ], async () => { variables.productAfter = ''; await refresh(); } ); return { pending, products, pageInfo, variables }; }