text: import React, { useState, useEffect } from 'react';
  import { useDispatch, useSelector } from 'react-redux';
  import Icon from 'react-native-vector-icons/MaterialIcons';
  import { FlatList, ActivityIndicator } from 'react-native';
  
  import api from '../../services/api';
  import { formatPrice } from '../../util/format';
  
  import * as CartActions from '../../store/modules/cart/actions';
  
  import {
    Container,
    Product,
    ProductImage,
    ProductTitle,
    ProductPrice,
    AddButton,
    ProductAmount,
    ProductAmountText,
    AddButtonText,
  } from './styles';
  
  export default function Main() {
    const [products, setProducts] = useState([]);
    const [loading, setLoading] = useState(false);
  
    const amount = useSelector(state =>
      state.cart.reduce((sumAmount, product) => {
        sumAmount[product.id] = product.amount;
  
        return sumAmount;
      }, {})
    );
  
    const dispatch = useDispatch();
  
    useEffect(() => {
      async function fetchData() {
        setLoading(true);
  
        const response = await api.get('/products');
  
        const data = response.data.map(product => ({
          ...product,
          formattedPrice: formatPrice(product.price),
        }));
  
        setProducts(data);
        setLoading(false);
      }
  
      fetchData();
    }, []);
  
    function renderProduct({ item }) {
      return (
        <Product>
          <ProductImage source={{ uri: item.image }} />
          <ProductTitle>{item.title}</ProductTitle>
          <ProductPrice>{item.formattedPrice}</ProductPrice>
          <AddButton
            onPress={() => dispatch(CartActions.addToCartRequest(item.id))}
          >
            <ProductAmount>
              <Icon name="add-shopping-cart" color="#FFF" size={20} />
              <ProductAmountText>{amount[item.id] || 0}</ProductAmountText>
            </ProductAmount>
            <AddButtonText>ADICIONAR</AddButtonText>
          </AddButton>
        </Product>
      );
    }
  
    return (
      <Container>
        {loading ? (
          <ActivityIndicator size={54} color="#eee" />
        ) : (
          <FlatList
            horizontal
            data={products}
            keyExtractor={item => String(item.id)}
            renderItem={renderProduct}
            showsHorizontalScrollIndicator={false}
          />
        )}
      </Container>
    );
  }
  