// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: MIT-0 import React, { useState, useEffect } from 'react'; import PropTypes from 'prop-types'; import * as config from '../../config'; // Components import Modal from '../modal/Modal'; // Mock data import { mockProductList } from '../../__test__/mocks/products-mocks'; // Styles import './ProductList.css'; const ProductList = (props) => { const [productId, setProductId] = useState(''); const [productsArr, setProducts] = useState([]); useEffect(() => { if (config.USE_MOCK_DATA) { const { products } = mockProductList.data; setProducts(products) } else { const url = config.GET_PRODUCTS_API; const options = { method: 'GET', headers: { Accept: 'application/json', }, }; fetch(url, options) .then(response => response.json()) .then(data => { const products = []; for (let i=0; i { return (a.id - b.id) }) // save the products in local store setProducts(products) }) .catch(() => { console.log('Error'); }); } }, []) useEffect(() => { scrollToCurrentProduct(); }) const handleProductClick = (productId) => { setProductId(productId) props.setModal(true); } const renderProductList = () => { const { currentProductId } = props; return ( productsArr.map(product => { const { id, name, price, discountedPrice } = product; let { imageUrl } = product; // if using mock data, refernce the images in the public folder if (config.USE_MOCK_DATA) { imageUrl = `${process.env.PUBLIC_URL}/${imageUrl}`; console.log(imageUrl); } const current = (currentProductId && currentProductId === id) ? 'product-current' : ''; const onSale = (price !== discountedPrice) ? 'product-onsale' : ''; return (
handleProductClick(id)}>
{id}
{name}
{`$${price}`} {onSale && ( {`$${discountedPrice}`} )}
) }) ) } const scrollToCurrentProduct = () => { const element = document.getElementsByClassName("product-current"); if (element.length) { element[0].scrollIntoView({ behavior: "smooth", block: "end", inline: "nearest" }); } } const closeModal = () => { props.setModal(false); } const { showModal } = props; return (
{renderProductList()}
{showModal && ( )}
); } ProductList.propTypes = { currentProductId: PropTypes.string, setModal: PropTypes.func, showModal: PropTypes.bool, }; export default ProductList;