1 | import { useContext, useMemo, useState, useEffect } from 'react';
|
2 | import { useQuery } from 'react-apollo';
|
3 | import { flattenList, getProductDetailForFlattenedProductList } from './list-transforms';
|
4 | import { ProductListContext } from './ProductListContext';
|
5 | import getErrorDetail from '../../helpers/getErrorDetail';
|
6 |
|
7 |
|
8 |
|
9 | export function useProductListItems(
|
10 | /** Passing null for id will retrieve the default product list */
|
11 | id = null, options = {}) {
|
12 | if (id && typeof id !== 'string')
|
13 | throw new Error('Product list id must be a string or null');
|
14 | const { state: { list }, queries, dispatch, usingLocalList } = useContext(ProductListContext);
|
15 | const [hydrated, setHydrated] = useState(!usingLocalList);
|
16 | const flattenedList = useMemo(() => flattenList(list), [list]);
|
17 |
|
18 | const productQueryResult = useQuery(queries.productsQuery, {
|
19 | skip: flattenedList.length === 0,
|
20 | errorPolicy: 'all',
|
21 | variables: {
|
22 | articleNumbers: flattenedList
|
23 | .map(listItem => listItem.articleNumber)
|
24 | .slice(0, options.limit)
|
25 | }
|
26 | });
|
27 |
|
28 | if (productQueryResult.error) {
|
29 | const { codes, data } = getErrorDetail(productQueryResult.error);
|
30 | if (codes.includes('ProductNotFound')) {
|
31 | for (const item of data) {
|
32 | dispatch({ type: 'REMOVE', payload: { articleNumber: item.argument } });
|
33 | }
|
34 | }
|
35 | }
|
36 |
|
37 |
|
38 | useEffect(() => {
|
39 | setHydrated(true);
|
40 | }, []);
|
41 | const result = {
|
42 | products: getProductDetailForFlattenedProductList(flattenedList, productQueryResult),
|
43 | loading: hydrated ? productQueryResult.loading : true
|
44 | };
|
45 | return result;
|
46 | }
|
47 |
|
\ | No newline at end of file |