简体   繁体   中英

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)


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

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 .

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

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.

Replace your Array.forEach to use Array.map . Because Array.forEach returns undefined but you expecting to have a new array.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM