how to set state array of object without removing old state

Viewed 3434

How to setState an array of objects in a single array without clearing the initial state.

const [arr,setArr]=useState([])

const arr1=[{key:'a',value:'a'},{key:'b',value:'b'}]
const arr2=[{key:'c',value:'c'},{key:'d',value:'d'}]

1st cycle setState
setArr((prevState)=>(prevState.push(...arr1)) // required state  arr=[{key:'a',value:'a'},{key:'b',value:'b'}]

2st cycle setState
setArr((prevState)=>(prevState.push(...arr2)) //  required state arr=[{key:'a',value:'a'},{key:'b',value:'b'},{key:'c',value:'c'},{key:'d',value:'d'}]


3 Answers

Array#push returns the length of the new array. Try using the spread operator instead:

setArr((prevState) => [...prevState, ...arr1]);
setArr((prevState) => [...prevState, ...arr2]);

setArr((prevState)=>(prevState.push(...arr1))

push will not return the modified array so you need to make sure that you return an array, like

setArr((prevState)=> [...prevState, ...arr1])

Note that you shouldn't do something like:

setArr((prevState)=> {
    prevState.push(...arr1)  
    return prevState;  // bad
})

because this would return a mutated array (which is bad because it may not cause a rerender) but not a new array

You can also create a new array before returning

setArr((prevState)=> {
    prevState.push(...arr1)
    return [...prevState]; // good
})

In your case, you can also use

setArr([...arr, ...arr1]);
setArr([...arr, ...arr2]);
Related