더보기 / 자동완성 기능 구현

thisisyjin·2023년 8월 17일
0

TIL 📝

목록 보기
88/113

더보기 버튼 기능 구현

  • 기존 데이터 보여주기 부분 리팩토링

const App = () => {
  const [allPokemons, setAllPokemons] = useState([]);
  const [displayedPokemons, setDisplayedPokemons] = useState([]);
  
  onst limitNum = 20; // 한 번에 보여지는 데이터 수 
  const url = `https://pokeapi.co/api/v2/pokemon/?limit=1008&offset=0`;
  
  // 중략
  
  // ✅ 더보기 버튼 onClick 시 -> 실제로 보여지고 있는 (20개씩 추가) 포켓몬 데이터만 필터링
  const filterDisplayedPokemonData = (allPokemonsData, displayedPokemons = []) => {
    const limit = displayedPokemons.length + limitNum; // 20 + 20 = 40
    const array = allPokemonsData.filter((_, index) => index + 1 <= limit); // index + 1이 limit(40)보다 작거나 같은 데이터 -> 0 ~ 40 까지
    
    return array; // 필터링 된 배열 반환
  }
  
  const fetchPokeData = async () => {
    // API 호출
  }
}

자동 완성 기능 구현

  • 검색 기능 리팩토링 진행.
  • 자동 완성을 위해서는 모든 데이터를 프론트단에서 들고있어야 함.

AutoComplete 컴포넌트 생성

App.js에서 AutoComplete에게 props로 allPokemons, setDisplayedPokemons 값을 넘겨줌.

const AutoComplete = ({allPokemons, setDisplayedPokemons}) => {

  return(
    <div>
      <form>
        <input 
          type="text" 
          value={searchTerm} 
          onChange={(e) => setSearchTerm(e.target.value)}
          /> 
        <button type="submit">검색</button>
      </form>
    </div>
  )  

}

검색 버튼 누를 때

const handleSubmit = (e) => {
  e.preventDefault(); // submit event prevent 
  let text = searchTerm.trim(); // 공백 제거
  setDisplayedPokemon(filterNames(text));
  setSearchTerm('');
} 

// input 값을 포함하는 데이터만 필터링함. 
const filterNames = (Input) => {
  const value = Input.toLowerCase();
  return value
  	? allPokemons.filter(e => e?.name.includes(value))   // value를 포함하는 애들만 남김 
    : []
}

자동 완성 기능

const checkEqualName = (input) => {
  const filteredArray = filterNames(input);
  
  return filteredArray[0]?.name === input ? [] : filteredArray;
  // 정확히 입력하면 자동완성 없어지게. 예> pikachu 다 입력 시 사라짐
}

...

return (
	// 중략	
  { checkEqualName(searchTerm).length > 0 && (
   		<ul>
     		{checkEqualName(searchTerm).map((e, i) => (
     			<li 
                  key={`button-${i}`} 
				  onClick={() => setSearchTerm(e.name)}
                >
         		  {e.name}
       			</li>
     		)}
   		</ul>
   	)
  }
)

profile
기억은 한계가 있지만, 기록은 한계가 없다.

0개의 댓글