0

Iam trying to render for Cars from my API. My problem is order in witch this fucntion is called.

export default function getGarage(arrayGarage) {
    fetch('http://127.0.0.1:3000/garage')
        .then(res => res.json())
        .then(res => {
            arrayGarage = res
            console.log(arrayGarage)
        })
    if (arrayGarage) {
        console.log(arrayGarage)
        return arrayGarage
    }
}
let arrayGarage = []
        arrayGarage = getGarage(arrayGarage)
        if (arrayGarage) {
            console.log('before while')
            for (let i = 0; i < arrayGarage.length; i++) {
                console.log('in  while')
                createCar(arrayGarage[i])
            }
        }

In first step I got an empty Array (from IF console in fetch), in second step I got "before while" and in third step I got array with my Cars(form then console). How to do that my 'while' wait for property from fetch and handle while.

[]            apiFunctions.js:13
before while         garage.js:43
(4) [{…}, {…}, {…}, {…}]   apiFunctions.js:10

Laaouatni Anas
  • 4,199
  • 2
  • 7
  • 26
DaroGawlik
  • 37
  • 5
  • you can use the `async await` syntax, maybe it will solve it like this https://stackoverflow.com/a/45018619/17716837 because fetch() take some time, so the variable wasn't successfully assigned meanwhile. basically, you need to wait these milliseconds then do the logic. or put the logic directly inside the `.then()` if you don't use `async await` – Laaouatni Anas Jan 01 '23 at 13:51

0 Answers0