Filter useState variable when input change

Viewed 18

I am using useState to store and change an array of pokemons.

When the input from a child component (<Search inputFilter={inputFilter} />) changes, I call handleOnChange in the Search component.

function handleInputChange(e) {
    const {value: searchValue} = e.target;
    setSearchValue(searchValue);
    props.inputFilter(searchValue);
}

So this will call the inputFilter from the parent (App.jsx).

function inputFilter(filterName) {
setPokemons(prevPokemons =>
  prevPokemons.filter(pokemon => pokemon.name.includes(filterName))); }

My problem is that when i delete a character, the pokemons array contains just the previous filtered pokemons. For example, if I type: "b", my array of pokemons will contain only those which have a b in their name. If I delete the character and the input is now empty, I want my previous array back, with all pokemons, not only the filtered ones.

Initial: Bulbasaur, Pikachu, Butterfree

After typing "B": Bulbasaur, Butterfree

After deleting "B" (input empty):

Expected: Bulbasaur, Pikachu, Butterfree

Actual: Bulbasaur, Butterfree

0 Answers
Related