I'm trying to implement search functionality on the Pokemon API, I have tried different methods but I cannot make it work for some reason.
My idea was to make a function that handles the changes on the event and then pass that to a hook(useState) and maybe make a get request and rerender?
I have this method for getting all Pokemons from the API. Should I make a new designed to filter the request?
export async function getAllPokemon(url) {
return new Promise((resolve) => {
fetch(url).then(res => res.json())
.then(data => {
resolve(data)
})
});
}
function App() {
....
const [filter, setFilter] = useState("");
function handleChange(event) {
setOption(event.target.value)
console.log(option)
}
const initialURL = `https://pokeapi.co/api/v2/pokemon?limit=50`
const handleSearchChange = (e) => {
setFilter(e.target.value);
};
useEffect(() => {
async function fetchData() {
let response = await getAllPokemon(initialURL)
await loadPokemon(response.results);
setLoading(false);
}
fetchData();
}, [option])
const loadPokemon = async (data) => {
let _pokemonData = await Promise.all(data.map(async pokemon => {
let pokemonRecord = await getPokemon(pokemon)
return pokemonRecord
}))
setPokemonData(_pokemonData);
}
return (
<>
<div >
<div>
<input
type="text"
id="header-search"
placeholder="Search Pokemon"
name="s"
onChange={handleSearchChange}
/>
<button >Search</button>
</div>
</div>
<div>
{loading ? <h1 style={{ textAlign: 'center' }}>Loading...</h1> : (
<>
<div className="grid-container">
{pokemonData.map((pokemon) => {
return <Card pokemon={pokemon} />
})}
</div>
</>
)}
</div>
</>
);
}
export default App;
You need to filter the array of Pokemon's that you are getting in your onChange. So something like
onChange = e = > {
setPokemons(pokemons.filter(pokemon => pokemon.indexOf(e.target.value) > -1))
}
So, this will toggle your local state variable that you are rendering on every key that is typed, which in turn will filter your array.