index.js

import React, { useEffect, useState } from 'react';
import useCocoApi from '../../hooks/fetch/request';
import ComedianList from '../../components/atoms/comedian-list';
import ComedianVideos from '../../components/atoms/comedian-videos';
import useSetMetaOgDescription from '../../hooks/share/useSetMetaOgDescription';
import SearchBar from '../../components/common/search-bar';

import './index.scss';

function removeDuplicates(videos) {
  const videosMap = new Map();
  videos.map((video) => {
    videosMap.set(video.videoId, video);
  });
  return Array.from(videosMap, ([_, value]) => value);
}

function filteredComedians(searchText, comedians) {
  return comedians.filter(({ name }) => name.toLowerCase().includes(searchText));
}

function filteredVideos(searchText, videos) {
  const filteredVideos = videos.filter(({ title }) => title.toLowerCase().includes(searchText));
  return removeDuplicates(filteredVideos);
}

function filterResults({ searchText, comedians, videos }) {
  return {
    filterdComedians: filteredComedians(searchText, comedians),
    filteredVideos: filteredVideos(searchText, videos)
  };
}

export default function Search() {
  const [searchText, setInput] = useState('');
  const [comedians, error_c] = useCocoApi({
    path: `/use/comedians`
  });
  const [videos, error_v] = useCocoApi({
    path: `/use/videos`
  });
  const [filterdComedians, setFilterdComedians] = useState([]);
  const [filteredVideos, setFilteredVideos] = useState([]);
  const placeholderText = 'Search Comedian or Standup Videos';
  const title = `${placeholderText} on comedy collection`;
  useSetMetaOgDescription({ content: title });

  const updateInput = async (input) => {
    setInput(input);
  };

  useEffect(() => {
    if (searchText.length > 3) {
      if (comedians?.length > 0 && videos?.length > 0) {
        const result = filterResults({ searchText: searchText.toLowerCase(), comedians, videos });
        setFilterdComedians(result.filterdComedians);
        setFilteredVideos(result.filteredVideos);
      }
    } else {
      setFilterdComedians([]);
      setFilteredVideos([]);
    }
  }, [searchText]);

  return (
    <div className="search-container">
      <SearchBar input={searchText} placeholderText={placeholderText} onChange={updateInput} />
      <div className="search-results">
        {filterdComedians.length > 0 && (
          <>
            <h2 className="title">Comedians</h2>
            <ComedianList comedians={filterdComedians} />
          </>
        )}
        {filteredVideos.length > 0 && (
          <>
            <h2 className="title">Videos</h2>
            <ComedianVideos videos={filteredVideos} error={error_v} />
          </>
        )}
      </div>
    </div>
  );
}