0

I don't know if I'm going to word this correctly, but here it goes... Working on building a Pokedex to learn a little React, with Hooks, I would like to be able to instantly search through the Pokemon. Now, I have merged two of the PokeAPI datasets together (pokemon and pokemon-species) in order to get all the content. Here is what I have:

UPDATED:

const [pokemon, setPokemon] = useState();
const [searchTerm, setSearchTerm] = useState('');
const [searchResults, setSearchResults] = useState([]);

const searchOnChange = e => {
  setSearchTerm(e.target.value);
  searchPokemon(searchTerm);
}

const searchPokemon = searchTerm => {
  setSearchResults(pokemon.filter(p => p.name.toLowerCase().includes(searchTerm.toLowerCase())));
  setPokemon(searchResults);
}

useEffect(() => {
  let species = [];
  let stats = [];

  axios.get('https://pokeapi.co/api/v2/pokemon-species?limit=151')
    .then(res => {
      return axios.all(res.data.results.map(p => axios.get(p.url)));
    })
    .then(res => {
      species = res.map(p => p.data);
        
      return axios.all(res.map(s => axios.get(s.data.varieties[0].pokemon.url)));
    }).then(res => {
      stats = res.map(p => p.data);

      setPokemon(species.map((p, i) => Object.assign({}, p, stats[i])));
    });
}, []);

Now, I know I need to add something for the search input like const [searchTerm, setSearchTerm] = useState('');, and have an onChange function setting the current value to the value of the input box, but I don't exactly know where to start as far as actually querying my Pokemon and outputting the results based on like terms.

Thanks in advance for any help/suggestions!

1 Answer 1

3

You're on the right path! If you want to query the PokeAPI with the new search term there must be a query parameter that you can set so that the API only sends back relevant data.

If you want to filter on the list you already have, a quick hint would be to use Array.prototype.filter method.

As the documentation states, this method filters an array by returning a new array that only contains the elements for which the evaluation function you pass in evals to something truthy.

This mean that if you have an array of objects like this:

{
  id: 1,
  name: 'pokemonName1'
}

Then you can get all the items in that array that match a certain condition (like name contains a substring) like this:

const nameFromInputField = 'pika'
myPokeArray.filter(pokemon => pokemon.name.includes(nameFromInputField));

Example:

const pokeData = [
  {
    id: 1,
    name: 'Pikachu'
  },
  {
    id: 2,
    name: 'Charmander'
  },
  {
    id: 3,
    name: 'Pichu'
  }
];

const searchTerm = "pi";

const filteredData = pokeData.filter(pokemon => pokemon.name.toLowerCase().includes(searchTerm.toLowerCase()));

console.log(filteredData);

Sign up to request clarification or add additional context in comments.

3 Comments

Thank for you help! I can't believe I didn't think about using the filter method. I have a couple of questions. I have updated the above code with my updated code with the search. I am having some issues. When I type a letter, the screen goes blank, and when I type a new letter, a filtered list with those matching the first letter appears. If I type another letter, once again it goes blank (even if there are matching entries. Why is it doing this? What am I doing wrong? Also, What would I need to do in order for it to render all Pokemon once someone has deleted all text from the input box?
I think this is because of the async nature of the setter returned by the useState method. When you call setSearchResult and on the next line call setPokemon, you are not awaiting for the searchResults to actually be set. What you'd want to try is to wrap your setPokemon call inside a useEffect with only searchResults in the dependency array
I ended up removing the searchResults state and just ended up filtering and mapping, not just mapping, the Pokemon. I'm always trying to over complicate things... THANK YOU!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.