Untitled

mail@pastecode.io avatar
unknown
plain_text
24 days ago
1.7 kB
4
Indexable
Never
  const [selectedValues, setSelectedValues] = useState<Set<string>>(new Set());
  const [updatedValues, setUpdatedSelectedValues] = useState<Set<string>>(
    new Set()
  );

  useEffect(() => {
    const filterValue =
      column?.getFilterValue() || (defaultOption ? [defaultOption.value] : []);
    const filterArray: string[] = Array.isArray(filterValue)
      ? filterValue
      : [filterValue].filter(Boolean);

    setSelectedValues(
      updatedValues.size === 0 ? new Set(filterArray) : updatedValues
    );
  }, [column, defaultOption, updatedValues]);

  const [isOpen, setIsOpen] = useState(false);

  const handleSelectOption = useCallback(
    (option: OptionString) => {
      const updatedSelectedValues = new Set(selectedValues);
      const isSelected = updatedSelectedValues.has(option.value);

      if (multiSelect) {
        if (isSelected) {
          updatedSelectedValues.delete(option.value);
        } else {
          updatedSelectedValues.add(option.value);
        }

        const filterValues = Array.from(updatedSelectedValues);
        column?.setFilterValue(filterValues.length ? filterValues : undefined);
      } else {
        if (isSelected) {
          if (column) {
            updatedSelectedValues.delete(option.value);
          }
        } else {
          updatedSelectedValues.clear();
          updatedSelectedValues.add(option.value);
        }

        column?.setFilterValue(isSelected ? undefined : option.value);
      }

      onOptionChange?.(option);
      setUpdatedSelectedValues(updatedSelectedValues);
    },
    [selectedValues, multiSelect, column, onOptionChange]
  );
Leave a Comment