index.js

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

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

export default function Comedians() {
  const listWrapperRef = useRef();
  const [comedians, error] = useCocoApi({
    path: `/use/comedians`
  });
  const [searchText, setInput] = useState('');
  const [filterdComedians, setFilterdComedians] = useState([]);
  const placeholderText = 'Search Comedians';
  const title = 'List of standup comedians';
  useSetMetaOgDescription({ content: title });
  useScrollTo({ stickStateName: 'comedians-page-ss', elementRef: listWrapperRef, dependencies: [comedians] });

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

  useEffect(() => {
    if (searchText.length > 1) {
      if (comedians?.length > 0) {
        const result = filteredComedians(searchText.toLowerCase(), comedians);
        setFilterdComedians(result);
      }
    } else {
      setFilterdComedians([]);
    }
  }, [searchText]);

  if (!comedians) return <Loading />;

  return (
    <div className="list-wrapper" ref={listWrapperRef}>
      <SearchBar input={searchText} placeholderText={placeholderText} onChange={updateInput} />
      {searchText.length > 1 ? <ComedianList comedians={filterdComedians} /> : <ComedianList comedians={comedians} />}
    </div>
  );
}