Advertisement
Guest User

components/pages/Product/CreateProduct/SelectItems.jsx

a guest
Feb 20th, 2020
107
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /* eslint-disable no-console */
  2. import React, { useEffect, useContext } from 'react';
  3. import Container from '@material-ui/core/Container';
  4. import { getEndpoint } from 'helpers/api';
  5. import Datatable from './Datatable';
  6. import { ProductConsumer } from './ProductContext';
  7.  
  8. const mapItemsWithOptionname = ({ options }) =>
  9.   options.map(o =>
  10.     o.items.map(i => ({ optionId: o._id, optionName: o.name, ...i }))
  11.   );
  12.  
  13. const mapOptionsItems = options =>
  14.   options.reduce((all, item) => [...all, ...item], []);
  15.  
  16. const mapAllItemsWithCheckedProp = items =>
  17.   items.map(item => ({ ...item, isChecked: false }));
  18.  
  19. const SelectItems = () => {
  20.   const { items, setItems } = useContext(ProductConsumer);
  21.   useEffect(() => {
  22.     const optionsEndpoint = getEndpoint('/options');
  23.  
  24.     fetch(optionsEndpoint)
  25.       .then(res => res.json())
  26.       .then(mapItemsWithOptionname)
  27.       .then(mapOptionsItems)
  28.       .then(mapAllItemsWithCheckedProp)
  29.       .then(_items => setItems(_items));
  30.   }, []);
  31.  
  32.   const handleCheckItem = index => {
  33.     setItems(
  34.       items.map((item, i) =>
  35.         i === index ? { ...item, isChecked: !item.isChecked } : item
  36.       )
  37.     );
  38.   };
  39.  
  40.   return (
  41.     <>
  42.       <Container maxWidth="xl">
  43.         <Datatable data={items} onCheckItem={handleCheckItem} />
  44.       </Container>
  45.     </>
  46.   );
  47. };
  48. export default SelectItems;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement