UNPKG

2.08 kBJavaScriptView Raw
1import { useContext, useMemo, useState, useEffect } from 'react';
2import { useQuery } from 'react-apollo';
3import { flattenList, getProductDetailForFlattenedProductList } from './list-transforms';
4import { ProductListContext } from './ProductListContext';
5import getErrorDetail from '../../helpers/getErrorDetail';
6/**
7 * Returns a list of products ready to be rendered
8 */
9export function useProductListItems(
10/** Passing null for id will retrieve the default product list */
11id = 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 // Make a `products` query containing every item in the list
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 // Remove the invalid item from the product list if it does not exist
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 // When using localStorage, we only want to display the list values after
37 // hydration, to avoid the initial server and client render being different
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//# sourceMappingURL=useProductListItems.js.map
\No newline at end of file