const App = () => {
const [pokemons, setPokemons] = useState([]);
const url = "https://pokeapi.co/api/v2/pokemon/?limit=1008&offset=0';
useEffect = (() => {
fetchData();
}, []); // 최초 한 번만 호출
const fetchData = async () => {
try {
const response = await axios.get(url);
setPokemons(response.data.results);
} catch (error) {
console.error(error);
}
}
}
const PokeCard = () => {
connst [pokemon, setPokemon] = useState([]);
// 중략
const bg = `bg-${pokemon?.type}`;
}
?.
: 옵셔널 체이닝.
옵셔널 체이닝
undefined
반환.undeclaredVar?.prop; // ReferenceError: undeclaredVar is not defined
<img src={imgSrc} loading="lazy" alt="hamster"/>
const fetchPokeData = async (isFirstFetch) => {
try {
const offsetValue = isFirstFetch ? 0 : offset + limit;
const url = `https://pokeapi.co/api/v2/pokemon/?limit=${limit}&offset=${offsetValue}`;
const response = await axios.get(url);
setPokemons([...pokemons, ...response.data.results]);
setOffset(offsetValue);
} catch (error) {
console.error(error);
}
}
// input onChange
const handleSearchInput = async (e) => {
setSearchTerm(e.target.value);
if (e.target.value.length > 0) {
try {
const response = await axios.get(`https://pokeapi.co/api/v2/pokemon/${e.target.value}`);
const pokemonData = {
url: `https://pokeapi.co/api/v2/pokemon/${response.data.id}`
name: searchTerm
}
setPokemons([pokemonData]);
} catch (error) {
setPokemons([]);
console.error(error);
}
} else {
// e.target.value.length === 0 인 경우
fetchPokeData(true); // isFirstFetch를 true로 넘겨줌
}
}