Skip to content

Instantly share code, notes, and snippets.

@Bitaru
Last active August 30, 2019 17:11
Show Gist options
  • Save Bitaru/8654754d6ce67d0c3bb02b1657f47531 to your computer and use it in GitHub Desktop.
Save Bitaru/8654754d6ce67d0c3bb02b1657f47531 to your computer and use it in GitHub Desktop.
/**
* @module components/ItemsList
*/
import React, { useState, useEffect } from 'react'
import ProductCard from 'components/Cards/Product'
import mapArray, { ArrayLike, MapArrayProps } from 'components/common/MapArray';
// Default item factory is using ProductCard
const ItemFactory = React.createFactory(ProductCard);
/** Props that ItemList view accepts */
export interface IItemsListProps extends MapArrayProps {
/** Wrapper around mapArray */
wrapper: React.ComponentType;
/** Rest props that are passed to wrapper */
[x: string]: any;
}
const fetchVariantMetaDataOfProduct: any = (item: any) =>
fetch(`${origin}${item.get('product_url')}`)
.then(function(response) {
return response.text()
})
.then(function(html) {
let parser = new DOMParser()
let doc = parser.parseFromString(html, "text/html")
let variantMetaData = Array.from(doc.querySelectorAll('.variant-meta-data')).map(function(element) {
return element.dataset
})
return variantMetaData;
})
const validateProductsInStock = (items) => {
const [products, setProducts] = useState([]);
useEffect(() => {
const fetch = async (item) => {
const variantPageMetaData = await fetchVariantMetaDataOfProduct(item);
if (item.get('title').trim() === "Mizzana Tote - Twisted Braid") {
// debugger;
}
const validVariants = item.get('variants').reduce((accumulator: any, variant: any) => {
const variantPageData = variantPageMetaData.find((variantMetaData) =>
Number(variantMetaData.variantId) === Number(variant.get('id'))
)
if (variantPageData.variantAvailable === "true") {
accumulator.push(variant);
}
return accumulator;
}, []);
item.set('variants', validVariants)
if (validVariants.length > 0 ) return item;
return;
};
Promise
.all(items.map(fetch).toArray())
.then(validVariants => setProducts(validVariants.filter(i => !!i)))
}, [])
return products;
}
export default ({ items, wrapper: Wrapper = React.Fragment, ...rest }: IItemsListProps) => {
const { limit, factory, keyAccessor, ...wrapperProps } = rest
const validProducts = validateProductsInStock(items);
console.log("items", items.get(0).toJS())
return (
<Wrapper {...wrapperProps}>
{ mapArray({ keyAccessor, limit, array: validProducts, factory: factory || ItemFactory, ...wrapperProps }) }
</Wrapper>
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment