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)
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.