import { GET_PRODUCTS } from '@graphql/queries/standalone/products'; import type { IProduct, IProductResponse } from '@types'; interface IProdArgs { categoriesSlugs: string; attributes?: string; productOrderBy?: string; minPrice?: number; maxPrice?: number; productAfter?: string; brand?: string; tags?: string; } interface IProdVars { productFirst: number; categoriesSlugs: string; attributes?: string; productOrderBy?: string; minPrice?: number; maxPrice?: number; productAfter?: string; brand?: string; tags?: string; } export function useStore(args: IProdArgs) { const variables = reactive({ productFirst: 12, categoriesSlugs: args.categoriesSlugs, attributes: args.attributes, productOrderBy: args.orderBy, minPrice: args.minPrice, maxPrice: args.maxPrice, productAfter: args.productAfter, brand: args.brand, tags: args.tags, }); const pending = ref(false); const products = ref([]); const pageInfo = ref<{ hasNextPage: boolean; endCursor: string; }>([]); const error = ref(null); const getProducts = async (): Promise => { pending.value = true; const queryVariables = { productFirst: variables.first, categoriesSlugs: variables.categoriesSlugs, productOrderBy: variables.orderBy || undefined, productAfter: variables.productAfter || undefined, attributes: variables.attributes || undefined, minPrice: variables.minPrice || undefined, maxPrice: variables.maxPrice || undefined, brand: variables.brand || undefined, tags: variables.tags || undefined, }; const { data, error: mistake } = await useAsyncQuery(GET_PRODUCTS, queryVariables); if (data.value?.products.edges) { pageInfo.value = data.value?.products.pageInfo; if (variables.productAfter) { products.value = [ ...products.value, ...data.value.products.edges, ]; } else { products.value = data.value?.products.edges; } } if (mistake.value) { error.value = mistake.value; } pending.value = false; }; watch(error, (e) => e && console.error('useStore products error', e)); return { pending, products, pageInfo, variables, getProducts, }; }