How to add Items to an existing array without affecting the current ones in React

I have a list item with a checkbox, Whenever the User clicks on the Checkbox it should add the value of that Checkbox to 2 arrays, but currently only one adds the values, the second keeps replacing the values, Here is my code

const handleToggle = (value) => () => {
const checked = books_numbers
let params = []

const currentIndex = checked.indexOf(value.value)


const newChecked = [...checked]
const newParams = [...params]


if (currentIndex === -1) {
    newChecked.push(value.value)
    newParams.push(value.params)
} else {
    newChecked.splice(currentIndex, 1)
}
}

so checked array is working just fine, when the user checks the box it will add the value, when the user unckecks the box it will remove that value from the array.

However params is not working, when the user checks the box (say the box value is 1,2)it will add that value to the params, but if he checks another box (say the value of the other book is 3,4) the params array will have only 3,4 and not 1,2 included, checking both boxes should add both boxes values to the Array

I have tried spread operator as seen in the codes it didn’t work, can anyone tell what is going wrong here or how can I fix that ?

Answer

On every call to the function you are re creating the params. Initialize it outside the function

let params = []
const handleToggle = (value) => () => {
const checked = books_numbers
  //... rest of code
}