import { useState, useEffect } from 'react';
import { Box, Typography, Button } from '@mui/material';
import { useSelector } from 'react-redux';
import Grid from '@mui/material/Grid2';
import { useNavigate } from "react-router-dom";
const ProductSuggestion = () => {
const [suggestProducts, setSuggestProducts] = useState([]);
const products = useSelector((state) => state.products.products.data);
const navigate = useNavigate();
useEffect(() => {
if (products.length > 0) {
const getRandomProducts = (arr, num) => {
const shuffled = [...arr].sort(() => 0.5 - Math.random());
return shuffled.slice(0, num);
};
const randomProducts = getRandomProducts(products, 4); // Select 4 random elements
setSuggestProducts(randomProducts);
}
}, [products]);
const renderProduct = (
handle,
img_url,
title,
collection_name,
minPrice,
minPriceCurrency,
maxPrice,
maxPriceCurrency,
extra_desc,
selected = false
) => {
return (
{
navigate(`/products/${handle}`)
}}
>
{selected && (
)}
{collection_name}
{title}
{`${minPriceCurrency} ${parseFloat(minPrice).toFixed(2)}`}
);
};
return (
{suggestProducts.map((product, index) => {
let {
handle,
title,
images,
collections,
minVariantPrice,
maxVariantPrice,
productType,
variants,
selected,
} = product;
let minPrice = minVariantPrice.amount;
let minPriceCurrency = minVariantPrice.currencyCode;
let maxPrice = maxVariantPrice.amount;
let maxPriceCurrency = maxVariantPrice.currencyCode;
let img_url = images[0]?.url;
let collection_name = collections[0]?.title;
return renderProduct(
handle,
img_url,
title,
collection_name,
minPrice,
minPriceCurrency,
maxPrice,
maxPriceCurrency,
"",
selected
);
})}
);
};
export default ProductSuggestion;