for loop gets multiple array from api and shows only one array for so many times

95 views Asked by At

im getting this error :

enter image description here

the function to get movies from api :

async function Movie(id){
    await fetch(`https://api.themoviedb.org/3/movie/${id}?api_key=84120436235fe71398e95a662f44db8b`)
        .then((res) => res.json())
        .then((json) => {
        name = json.original_title;
        img = json.poster_path;
        link = name.replace(/[^a-zA-Z\s/ ]/g, "");
        var MyArray = {'name':`${name}`, 'img':`${img}`, 'link':`/movies/${link}.html`}
        console.log(MyArray)
        })
        .catch(err => {
            console.error(err);
        });
}

the array of movies :

const MyMovies = [
    Movie(238),
    Movie(899082),
    Movie(899),
]

the function to load the movies :

async function LoadMovies(){
    buildTable(MyMovies)
    function buildTable(data){
        var table = document.querySelector('#movies')
        for (var i = 0; i < data.length; i++){
            var row = `<img id="img" src="${'https://image.tmdb.org/t/p/w342/' + img}" alt="${name}" class="thumb" onclick="location.href='${link}'">`
            table.innerHTML += row
        }
    }
}
1

There are 1 answers

0
bob On BEST ANSWER

You're continually overwriting ing, link, name in the global context... you'll have to isolate these... I recommend using a class, so each movie can have it's own set of unique values... You'll have to kind of re-think your approach though: // added json to finalize

class Movie {

    constructor(id) {
        this.id = id;
        this.load();
    }
    finalize(json) {
        this.name = json.original_title;
        this.img = json.poster_path;
        this.link = name.replace(/[^a-zA-Z\s/ ]/g, "");
        var MyArray = { 'name': `${this.name}`, 'img': `${this.img}`, 'link': `/movies/${this.link}.html` }
        console.log(MyArray)
    }

    async load() {
        await fetch(`https://api.themoviedb.org/3/movie/${this.id}?api_key=84120436235fe71398e95a662f44db8b`)
            .then((res) => res.json())
            .then((json) => {
                this.finalize(json)
            })
            .catch(err => {
                console.error(err);
            });
    }

}


const MyMovies = [
    new Movie(238),
    new Movie(899082),
    new Movie(899),
]

async function LoadMovies() {

    // var table = document.querySelector('#movies')
    for (var i = 0; i < MyMovies.length; i++) {
        var item = MyMovies[i];
        console.log("img", item.img);
        console.log("name", item.name);
        console.log("link", item.link);

        // var row = `<img id="img" src="${'https://image.tmdb.org/t/p/w342/' + item.img}" alt="${item.name}" class="thumb" onclick="location.href='${item.link}'">`
        // table.innerHTML += row
    }

}