0

so i want to store the state of an array with an unknown length.

so basically the user can choose between 2,3 or 4 players and then he will be asked to enter their names the problem is that i couldn't find a way to store their names inside a value of a useState with an array type.

mouhib
  • 85
  • 1
  • 8
  • Does this answer your question? [Sort array of objects by string property value](https://stackoverflow.com/questions/1129216/sort-array-of-objects-by-string-property-value) – caslawter Jul 18 '22 at 07:50

1 Answers1

0

You absolutely can. Just destructure the previous value of the array and add in your new player.

setPlayer([...prevPlayers, newPlayer])
caslawter
  • 631
  • 1
  • 6
  • 11
  • the problem is that i need the values to be in order so i can know the name of each player by index. for example the player 1 will have the name of the index 0 from the array – mouhib Jul 17 '22 at 18:02
  • 1
    You will have to write a sorting algorithm to sort the players based on their id before setting the state. It has already been answered. https://stackoverflow.com/questions/1129216/sort-array-of-objects-by-string-property-value – caslawter Jul 18 '22 at 07:49