0

i have thi problem, i fetch images from an api and stock them in an array. When i log the array i have the result but when i want to enter one element of the array i have 'undefined'

'''
entry_point = "http://localhost:8000/api/v1/titles/"

    function get_data(genre, page) {
        let datas = [];
        fetch(entry_point + '?genre=' + genre + '&page=' + page)
            .then(res => res.json())
            .then(data => data.results.forEach(element => { datas.push(element) }));
        return datas;
    }
    
    let array = get_data('Action', 1)
    
    console.log(array) ======> log the array correctly
    console.log(array[0]) =====> returns 'undefined'
'''
    
Arthur
  • 13
  • 4
  • Can you put console.log(array) in second last line and check. It does not show in your code – Tushar Shahi Sep 22 '21 at 07:13
  • `fetch` is asynchronous so you cannot return the `datas` directly. You need to `await` for the `fetch` to complete. – Gabriele Petrioli Sep 22 '21 at 07:14
  • you have do use async/await because of asynchronous - at runtime it is correct of undefined because of asynchronous http call – Alexander Peinsipp Sep 22 '21 at 07:16
  • Thanks, but shouldn't then() method do this of awaiting for the response? in addition the function works because i can log the array. It is when i enter an element of the array that i get 'undefined' – Arthur Sep 22 '21 at 09:34

0 Answers0