0

I am trying to create synchronous looping using fetch in react native.

This is the reference I took from here:

loop fetch in reactjs

apiCallConfigFetch = async () => {
    var item = 0
    global.configDetails = []
    var temp = {}

    console.log(global.userLocationID)
    for (item = 0; item < global.userLocationID.length; item++) {
      const response = await fetch(global.locationConfigUrl, {
        method: 'POST',
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          locationID: global.userLocationID[item]
        }),
      })
      const data = await response.json()
      if (data == '') {

      } else {
        temp['locationID'] = data['id']
        temp['name'] = data['name']
        temp['configuration'] = data['configuration']
        global.configDetails.push(temp)
        console.log(global.configDetails)
      }
    }
  }

This is my code

I want to replicate synchronous behaviour. The array in which I am pushing the data is taking the last element as repeat due to function's async behaviour. I have tried async but it's not working. Any help will be much appreciated. I have used the solutions in the answer but it's not working.

  • Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Jared Smith Aug 22 '19 at 18:11
  • There are a lot of problems here: modifying a global with async fetches in a loop, capturing a variable mutated by a loop in a closure, weird mixture of dot property and square bracket accesses, loose equality check, no semi-colons, uses a global instead of a parameter. Hard to test, hard to read, hard to fix. – Jared Smith Aug 22 '19 at 18:14
  • I know it's a duplicate question. It's just that I am not able to create synchronous behaviour in it. Can you please guide me in fixing the problems in the code? It would be much appreciated!! – Vedant Bajaj Aug 23 '19 at 06:04
  • Have a look at this https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all. – Jared Smith Aug 23 '19 at 11:52
  • I solved it using promises. I have attached the reference. https://stackoverflow.com/a/49990254/11887992 – Vedant Bajaj Aug 26 '19 at 09:08

0 Answers0