0

I have a React component that gets an array of ids (strings) from props as subs, and what I want it to do is for every id in the array, get it's data from the server and save it in another array SubscribedMembers using useState. Here's my code:

import {useState , useEffect} from 'react'
import axios from 'axios'

function Subs({subs}) {
  const [SubscribedMembers, setSubscribedMembers] = useState([])

  const getMember = async (id) => {
    let {data} = await axios.get("http://localhost:8000/api/members/" + id)
    setSubscribedMembers([...SubscribedMembers , data])
  }

  useEffect(() => {
    subs.map(async (x) => {
      await getMember(x)
    })
  } , [subs])

  const subsMap = SubscribedMembers.map(member => {
    return <li key={member._id}>{member.name}</li>
  })

  return (
    <div>
      <ul>{subsMap}</ul>
    </div>
  )
}

export default Subs

The problem is, while I expect the setSubscribedMembers function inside the getMember function to set the previous data and the new one each iteration, it only sets the last one (or just one, every time it's something else)

What am I doing wrong here?

  • I think it's happening because of async await. As your function isn't waiting for data to arrive from api and continuing it's execution for next loop of map. So even before api responds for first value, function is getting called for last value with blank list. All of your requests are getting blank lists for same reason and the most recent update will be of last element. Please try to take large number of elements in list of ids and see if there's any difference considering list may get update once before last element arrives – Jake Peralta Apr 26 '22 at 21:34

0 Answers0