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
CodePudding user response:
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
.
CodePudding user response:
In this change:
const newData = res.data.forEach(item) => {
What are you expecting forEach()
to return and why? Taking a step back... You already have working code, so just use your known working code. Since the React component declares an array
variable already, the only change you need to make is to rename your local variable:
const newArray = []
res = await getData()
res.data.forEach(item) => {
newArray.push({
...item,
isSelected: false,
id: getItemId(item.id)
})
})
Then just update state to your new array:
setArray(newArray);
CodePudding user response:
Here is an approach:
const newData = res.data.map((item)=>{
return {
...item,
isSelected: false,
id: getItemId(item.id)
}
})
setArray(newData)
This will modify the value of the state .
CodePudding user response:
Replace your Array.forEach to use Array.map. Because Array.forEach
returns undefined
but you expecting to have a new array.
CodePudding user response:
I suppose that you should use useEffect
rather than useCallback
when fetching/editing data inside the component. In react you can write like this;
async function handleFetch() {
const res = await getData();
const newData = res.data.map((item) => {
return [{ ...item, isSelected: false, id: item.id }];
});
setArray(newData);
}
useEffect(() => {
handleFetch();
}, []);
to mock data I wrote this ;
function getData() {
return { data: [{ isSelected: true, id: 1 }] };
}
And you can check out stackblitz link