1

I found a solution to push elements to an array state (Push method in React Hooks (useState)?)
But as you see below, setTheArray is inside a callback. So the order of theArray depend of the callback time.
How to preserve order of theArray based on service_months's order ?

useEffect(() => {
  for (const service_month of service_months) {
    GET(`/api/report/${props.user_id}`, service_month, resp => {
      setTheArray(oldArray => [...oldArray, resp.data])
    })
  }
}, [service_months])
Unviray
  • 162
  • 1
  • 10
  • 1
    You might be able to immediately insert a placeholder element and then replace it with the real value once it arrives, though there may be better approaches. – DBS Sep 21 '21 at 12:59

1 Answers1

2

One way to do this would be to convert the callback to a Promise and also minimise state changes on every report using something like this:

const GETAsync = (URL, val) => {
  return new Promise((resolve) => {
    GET(URL, val, (resp) => {
      resolve(resp.data)
    })
  })
}

useEffect(() => {
async function updateState() {
  const data = await Promise.all(
    service_months.map((service_month) =>
      GETAsync(`/api/report/${props.user_id}`, service_month)
    )
  )

  setTheArray((oldArray) => [...oldArray, ...data])
}

updateState()
}, [service_months])
Unviray
  • 162
  • 1
  • 10
Ryan
  • 5,229
  • 1
  • 20
  • 31