I don't understand what the concat method is doing in this instance (Redux Flashcards)

The provided starter code for the Flashcards project has this line:

  const addCardInputs = (e) => {
    e.preventDefault();
    setCards(cards.concat({ front: "", back: "" }));    
  };

I don’t understand what concat is doing in this instance and this function isn’t worked on during the project, its just provided and then left alone. It seems like this should add the card to the local ‘cards’ state and then clear the inputs. I’m not sure if this is destructuring either, there’s no function arguments so I just don’t know what’s going on here.

Here’s a github project of someone else’s work for context. The line I’m wondering about is 65

https://www.codecademy.com/paths/advanced-react-redux-sp/tracks/advanced-react-redux-sp-redux/modules/redux-challenge-project/projects/react-redux-flashcards

This function creates new empty input fields for the card front and the card back on the Qizzes → Create a new Quiz route. It concatenates the new empty card with the already edited and submitted cards in the cards array in order to avoid a nested array or loose the previous state. Once you typed a value into the empty card’s back and front and press the submit button, the updateCardState function is called and just updates the value of the cards without adding the new card to the cards state because that already happened in the addCardInputs function.

What in my opinion makes this function a little difficult to understand is that an array is concatenated with an object. If you write this, the same would happen:

setCards(cards.concat([{ front: "", back: "" }]));

You could also write it like this (which would be more in line with the other lessons about updating state):

setCards(prev => [...prev, { front: "", back: "" }]);

Hope it’s clearer now?

1 Like