0

So I will try to give as much information as possible but if you need more I can provide it.

I am making a website that has a dropdown which inside it has some options from an array, lets say there are 4 for this example A, B, C and D. Now this dropdown works great by returning the selection I have made to this function below.

//Array example 
letterArray = [
        {letter: "A"},
        {letter: "B"},
        {letter: "C"},
        {letter: "D"}
    ]

    function changeLetter(value){
        console.log(value.letter); // This returns whichever one I selected nicely so if i click A in the dropdown i get A back.
    }

Imagine I am building a word of 4 letters lets say "ABCD" to keep it simple, what I need to do is render 4 of my dropdowns. On page load I only render 1 because I do not know the length of the word the user wants to make. I have something like this to map them.

{numberOfLetters.map((_, index) => {
   return(
    <div key={index}
      <LetterSelection 
      onChange={changeLetter} /> //THIS IS MY DROPDOWN COMPONENT
    </div>
    )
})

I then have a button which increases the count of numberOfLetters to increase the array which makes the map longer. This all works fine still...

My attempt at getting this to work is like so, I change my function to have a state like this.

const [array, setArray] = useState([]);
function changeLetter(value){
   setArray(oldArray => [...oldArray, {option: value.letter}])
   console.log(array);
}

This pushes my selection to the array nicely and almost giving me what I want.

THE PROBLEM

If the user then decides to change the selection from say "A,B,C,D" to "A,C,B,D" another letter gets added to the array effectively becoming "A,B,C,D,C". I thought about using splice here to only get the 4 I want but it then misses out one of the user selected options(Not the correct one!).

So how do i get it so it updates the correct selection rather than adding a new object to the array?

Can post more code if needed.

Matt
  • 541
  • 1
  • 12

0 Answers0