psquizzle
psquizzle

Reputation: 185

React UseState hook, unable to concatenate arrays

I am encountering some strange behavior when attempting to add two arrays together in react. Each array chunk has a length of 50 items. My list never grows beyond 50.

I have tried both with spread operator and concat method, with and without wrapper functions. nothing works

setWordList(wordList => wordList.concat(msg))
setWordList(wordList => [...wordList, msg]) 
setWordList([...wordList, msg]) 
setWordList(wordList.concat(msg)) 
  const [wordList, setWordList] = useState([])
  const [isSearching, setIsSearching] = useState(true)


  
  const loadMoreList = (data) => {
    console.log(data)
    setIsSearching(true)
    let already = []
    for(let i = 0; i < wordList.length; i++){
      already.push({_id: wordList[i]._id})
    }
    console.log(already)
    socket.current.emit('get word list more', {filter: data.filter, already: already});
  }

  

  socket.current.on('word list in', (msg) => {
  
    setWordList(wordList => [...wordList, msg])
    
    console.log(msg)
    setIsSearching(false)
   
  });

Example data(array length = 50)

[{
definition: "1. aufhören zu leben, sein Leben beschließen↵Beispiele↵“jung sterben”↵Wendungen, Redensarten, Sprichwörter↵“zum Sterben langweilig, müde, einsam o. Ä...."
id: "dfe03030-0c50-11ea-afa4-098be982e090"
leitner_no: 2
priority: true
priority_time: 1587986213134
reviews: 1
source: "manual"
source_details: "none"
time_stamp: 1583402873665
word: "sterben  | starb, gestorben |"
_id: "fb99b7c3-34a4-4e63-a98e-41efbbcfe5fc"}]

The current list and incoming data never concatenate, the new data seems to replace that in the list already. Console.log of wordList within socket('word list in') returns an empty list regardless of whether there is data rendered from the previous input. Somehow the state appears to not be persisting. Any help would be greatly appreciated.

Upvotes: 6

Views: 11627

Answers (2)

Hcosta
Hcosta

Reputation: 11

If you want just a single array with the concatenated items you would use :

setWordList(wordList => [...wordList, ...msg])

and the outcome would be : ["banana", "orange", "apple", "..."];

However if you were looking to have an array of arrays...then you would want to :

setWordList(wordList => [...wordList, msg])

Then the outcome would be : [[...array1],[...array2],[...whatever]];

Upvotes: 1

Rohan Agarwal
Rohan Agarwal

Reputation: 2609

Both the array needs to be spread, like this:

setWordList(wordList => [...wordList, ...msg])

Upvotes: 18

Related Questions