When I change data in element by id in array object, it duplicated to all elements

31 Views Asked by At

I just started using react.To store data, I use an array of objects. I specially created it of a certain length(100), so that using id to safely add user responses (id is out of order, you can answer 1 and then 3). I wrote a function that adds a row to 0 array element (the array cannot be removed, it is used) But for some reason the value of the elements is duplicated for the entire array. Why does it happen and how to fix it???

Variables

  const [ans,setAns] =useState(Array(100).fill({
    Answer:[''],

}))

Function

 function SetWordAnswer(answer) {
    let next = [...ans];
    next[0].Answer[0] =answer
    setAns(next)
    console.log(next)
}

Element in html

   {VariableData.type === 'WordAnswer' ?
   <input placeholder="ответ" type="text" value={ans[variableId-1].Answer[0]} className="my-4 p-2 text-gray-50 bg-gray-900 rounded-full" onChange={(event)=>{SetWordAnswer(event.target.value)}}/>: ''}

Used Data Link

New Data after function Link

1

There are 1 best solutions below

0
Pointy On

You can fill the array with a dummy value and then use .map() to fill it with distinct objects of the form you want:

const [ans,setAns] = useState(Array(100).fill(null).map(() => ({
    Answer:['']
})));

The elements will initially all look alike, but they will be distinct objects.