Untitled
unknown
javascript
a month ago
3.7 kB
5
Indexable
Never
import Card from "./Card"; import { RESTAURANT_DATA } from '../utils/constants'; import { useState, useCallback, useEffect } from "react"; const BUTTON_STATES = { topRated: false, sortByRatings: false, sortByDeliveryTime: false, } export default CardsContainer = () => { const [resData, setResData] = useState([...RESTAURANT_DATA]); const [buttonStates, setButtonStates] = useState(BUTTON_STATES); const sortingByPreference = useCallback(() => { let sortedArrayOfRestaurant = [...RESTAURANT_DATA]; if(buttonStates.topRated){ sortedArrayOfRestaurant = sortedArrayOfRestaurant.filter(res => res.info.avgRating >= 4) } if(buttonStates.sortByDeliveryTime){ sortedArrayOfRestaurant = sortedArrayOfRestaurant.sort((firstResData, secondResData) => firstResData.info.sla.deliveryTime - secondResData.info.sla.deliveryTime) }; if(buttonStates.sortByRatings){ sortedArrayOfRestaurant = sortedArrayOfRestaurant.sort((firstResData, secondResData) => secondResData.info.avgRating - firstResData.info.avgRating) } return sortedArrayOfRestaurant; }, [buttonStates, RESTAURANT_DATA]); useEffect(() => { setResData(sortingByPreference()); }, [buttonStates]); const onClickHandler = ({ buttonClickType, resetButton }) => { if(!resetButton){ if(buttonStates[buttonClickType]) { setButtonStates((prevButtonState) => { return { ...prevButtonState, [buttonClickType]: false } }); } else { setButtonStates((prevButtonState) => { return { ...prevButtonState, [buttonClickType]: true } }); } } else { setButtonStates({...BUTTON_STATES}); } } const shouldAllRestaurantsButtonBeEnabled = () => { for(property in buttonStates) { if(buttonStates[property]){ return true; } } return false; } return (<> <div className="top-rated-btn"> <button onClick={() => onClickHandler({ resetButton: true })} className={shouldAllRestaurantsButtonBeEnabled() ? 'red': ''} disabled={!shouldAllRestaurantsButtonBeEnabled()}>All Restaurants</button> <button onClick={() => onClickHandler({ buttonClickType: 'topRated'})} className={buttonStates.topRated ? 'blue': 'red'}>Top Rated Restaurants</button> <button onClick={() => onClickHandler({ buttonClickType: 'sortByRatings'})} className={buttonStates.sortByRatings ? 'blue': 'red'}>Restaurants(By Ratings)</button> <button onClick={() => onClickHandler({ buttonClickType: 'sortByDeliveryTime'})} className={buttonStates.sortByDeliveryTime ? 'blue': 'red'}>Restaurants(By Delivery Time)</button> </div> <div className="cards-container"> { resData.map( (restaurant) => <Card key={restaurant?.info?.id} imgSrc={restaurant?.info?.cloudinaryImageId} avgRating={restaurant?.info?.avgRating} costForTwo={restaurant?.info?.costForTwo} cuisines={restaurant?.info?.cuisines} name={restaurant?.info?.name} areaName={restaurant?.info?.areaName} deliveryTime={restaurant?.info?.sla?.deliveryTime} />) } </div> </> ); };
Leave a Comment