GDelsaux
GDelsaux

Reputation: 101

How can I sort an array of objects by ID?

I am using PokeAPI in react using axios to get the data.

When making my first request the pokemon order is as expected (1, 2, 3...)

when looping over each object in the array to get more details (img, moves and so on) and pushing each iteration into an array, the pokemon order is all over the place.

ex: 1st array

[
0: {name: 'bulbasaur', url: 'https://pokeapi.co/api/v2/pokemon/1/'}
1: {name: 'ivysaur', url: 'https://pokeapi.co/api/v2/pokemon/2/'}
2: {name: 'venusaur', url: 'https://pokeapi.co/api/v2/pokemon/3/'}
... ]

2nd array (note this isn't the actual result as it would be too long and irrelevant to type in)

[
0: {name: pikachu, id: 10}
1: {name: charmander, id: 3}
... ]

What I want to achieve essentially is getting my second array in the same order as the same one.

here is the -edited- code

  useEffect(() => {
    setLoading(true);
    let cancel;
    axios.get(currentPageUrl, {
      cancelToken : new axios.CancelToken(c => cancel = c)
    }).then(res => {
      setLoading(false);
      setNextpageUrl(res.data.next);
      setPreviousPageUrl(res.data.previous);
      //this array is in the expected order
      console.log(res.data.results)
      res.data.results.forEach(async (pokemon) => {
        const res = await axios.get(`${pokemon.url}`);
        //this is the array I am having an issue with
        setPokemons(list => [...list, res.data]);
      })
      return () => cancel();
    })
  }, [currentPageUrl]);

Thank you in advance

Upvotes: 0

Views: 472

Answers (1)

TheTisiboth
TheTisiboth

Reputation: 1651

Since you are doing async operations, you can not guaranty that you will have the same order. You better use Promise.all, so you resolve all the promises, but then it keeps the same order.

//This array is in the expected order
console.log(results)
const pokemonPromises = results.map(pokemon => axios.get(`${pokemon.url}`))
const pokemons = await Promise.all(pokemonPromises)
setPokemons((currentArray) => [...currentArray, ...pokemons])

Upvotes: 1

Related Questions