SubCategoryChips.js 1.64 KB
import Image from "next/image";
import React, { useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { setActivityFilters } from "../../redux/actions/activityAction";

const SubCategoryChips = ({ data }) => {
  const dispatch = useDispatch();
  const { activityFilters } = useSelector(sate => sate.activityFilters);
  const [select, setselect] = useState(activityFilters.subCategories?.includes(data.id));

  useEffect(() => {
    setselect(activityFilters.subCategories?.includes(data.id));
  }, [activityFilters]);

  return (
    <div>
      <a
        onClick={() => {
          setselect(!select);
          if (activityFilters.subCategories.length > 0) {
            if (activityFilters.subCategories.includes(data.id)) {
              let newArr = activityFilters.subCategories.filter(item => item != data.id);
              dispatch(setActivityFilters({ filters: { ...activityFilters, subCategories: newArr } }));
            } else {
              dispatch(setActivityFilters({ filters: { ...activityFilters, subCategories: [...activityFilters.subCategories, data.id] } }));
            }
          } else {
            dispatch(setActivityFilters({ filters: { ...activityFilters, subCategories: [data.id] } }));
          }
        }}
        //   key={index} onClick={() => handleToggleCloseIcon(index)}
      >
        <span>{data.attributes.name}</span>
        {select && (
          <span className="image-container">
            <Image layout="fill" alt="image" className="image" src="/images/icons/close-button.svg" />
          </span>
        )}
      </a>
    </div>
  );
};

export default SubCategoryChips;