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])
1
  • 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. Commented Sep 21, 2021 at 12:59

1 Answer 1

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])
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.