Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I use forEach to push into an array with React useState?

I’m trying to use the same code below in React. I’ve tried a couple ways but it doesn’t work the same way.

working old code (not react code)


const array = []
res = await getData()

res.data.forEach(item) => {
array.push({
   ...item, 
   isSelected: false, 
   id: getItemId(item.id) 
})

not working new code (React)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel


const [array, setArray] = useState([])

const fetchItems = useCallback(async () => {
res = await getData()
const newData = res.data.forEach(item) => {
return [{...item, isSelected: false, id: getItemId(item.id) }]
})

setArray(newData)

}, [])

fetchItems()
console.log(array)

Is there a clean way to write this the same way it was done in the working code? Preferably without using push

>Solution :

try

const fetchItems = useCallback(async () => {
    res = await getData()
    const tempArr = res.data.map(item => ({...item, isSelected: false, id: 
    getItemId(item.id) }))
    setArray(tempArr)
}, [setArray, getData, getItemId])

but make sure your functions getData, getItemId wont change by wrapping them with useCallback as well or avoid using useCallback.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading