Home > Back-end >  Spread operator in a function retrun
Spread operator in a function retrun

Time:09-01

I am having some trouble interpreting what is going on in a specific piece of code in reactJS and was wondering if anyone is able to point me in the right direction.

const [allPokemons, setAllPokemons] = useState([]);

  const getAllPokemons = async () => {
    const res = await fetch(
      'https://pokeapi.co/api/v2/pokemon?limit=649&offset=0'
    );
    const data = await res.json();

    function createPokemonObject(results) {
      results.forEach(async (pokemon) => {
        const res = await fetch(
          `https://pokeapi.co/api/v2/pokemon/${pokemon.name}`
        );
        const data = await res.json();

        setAllPokemons((currentList) => [...currentList, data]);
        await allPokemons.sort((a, b) => a.id - b.id);
      });
    }
    createPokemonObject(data.results);
  };

  useEffect(() => {
    getAllPokemons();
  }, []); 

I'm specifically confused about this line of code:

setAllPokemons((currentList) => [...currentList, data]);

I have usually seen the spread operator used in the parameter but not in this manner. If anyone can shed some light on what is going on here would be great or point me in the direction to look into this usage more deeply.

Here's my codebase if you need more context: https://github.com/lojickse7en/pokedex-app

CodePudding user response:

In this case, the spread operator is used to make a copy of the list and add additional elements. So, if your currentList is ['foo', 'bar', 'baz'], your arrow function, ((currentList) => [...currentList, 'buz']) unpacks to ((currentList) => ['foo', 'bar', 'baz', 'buz']). The newly created array is returned. The difference between just appending to an array (currentList.push('buz')), and creating it the way you see in your example, is that in the first case you create a side-effect of changing the original array. This isn't the end of the world, but a tenet of Functional Programming is the idea that pure functions shouldn't produce side-effects (changes outside of their function body). Using the spread operator as shown above allows us to return a new array instead of altering the existing one.

CodePudding user response:

It just means to construct a new list with the current list and add "data" to it.

e.g.

> a = [1,2,3]
[ 1, 2, 3 ]
> [ ...a, 4,5 ]
[ 1, 2, 3, 4, 5 ]
>

CodePudding user response:

It is spreading the values of an iterable, and the second passed value adds more data to the existing list. e.g push or concat.

a = [1,2,3,4,5]
s = [...a, 2,6,8]

will result to [1, 2, 3, 4, 5, 2, 6, 8]

  • Related