2

I had an array with 10 item First, I added 5 item in useState

const [dataList, setDataList] = useState([])
useEffect(() => {
  const newArr = []
  for (var i = 0; i < 5 && i < data.length; i++) {
       newArr.push(data[i])
      }
      setDataList(newArr)
    }, [])

Then, when I added 5 item left, I got not expect result

onPress = () => {
    const newArr2 = []
    for (var i = 5; i < 10 && i < data.length; i++) {
        newArr2.push(data[i])
    }
    setDataList([...dataList, newArr2])
    console.log("dataList", dataList)
}

https://i.sstatic.net/lB0JD.png

How can I push 5 item left into the useState array? Sorry for my bad English.

2 Answers 2

3

The alternative to spread syntax could be:

setDataList(dataList.concat(newArr2))
Sign up to request clarification or add additional context in comments.

Comments

3

You are spreading your current array, but not the new one:

setDataList([...dataList, ...newArr2])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.