Fetching data for the autosuggest
You might have guessed till now, that we will be using the useEffect React hook here. As soon as the component is mounted, we will be fetching the pokemon data asynchronously.
For data, we will be consuming this API.
Note: For folks coming from the Class component world of React, useEffect will be used here as the componentDidMount function.
Let us fetch 20 pokemons and we will create a state called options.
Just below the searchText state declaration,
const [options, setOptions] = useState([]);
useEffect(() => {
const pokemon = [];
const promises = new Array(20)
.fill()
.map((v, i) => fetch(`https://pokeapi.co/api/v2/pokemon-form/${i + 1}`));
Promise.all(promises).then(pokemonArr => {
return pokemonArr.map(value =>
value
.json()
.then(({ name, sprites: { front_default: sprite } }) => {
console.log({ name, sprite })
pokemon.push({ name, sprite })
})
);
});
setOptions(pokemon);
}, []);
// empty dependency array signifies that this will be called only once after the component has mounted
new Array(20).fill() will create an array of 20 elements, all undefined. I will be calling the api 20 times (sorry but that is how it has been configured). Resolving all the promises, I will set my options state to the pokemon array containing name of the pokemon and its sprite (image).
Because, we are logging the data in the console, you will be able to see the data in the browser console.

4
