Appending array of items to array of items in React state

Viewed 47

I initialised state like this:

const [titles, setTitles] = useState([])

I'm appending another array of items data.titles to the array titles in a loop like this:

setTitles(titles => [...titles, data.titles])

and I have also tried this:

setTitles([...titles, data.titles])

but both don't seem to work, because when I'm printing titles in the console after the loop is done, an empty array is displayed. What am I missing here?

1 Answers

You shouldn't use the previous state directly while setting the new state as state changes are asynchronous. Also, Since your second param (data.titles), is an array, you should iterate through it too using the spread operator.

setTitles(prevState => [...prevState, ...data.titles])

A simpler way to do this would be using the array concat operator,

setTitles((prevState) => prevState.concat(data.titles));
Related