card.js
export class Cards {
constructor(domain, topic, limit) {
this.domain = domain;
this.after = '';
this.topic = topic;
this.limit = limit;
}
addCards(parentElement) {
let url = `https://www.${this.domain}.com/r/${this.topic}.json?after=${this.after}&limit=${this.limit}`;
fetch(url).then(function(response) {
return response.json();
})
.then(function(data) {
this.after = data.data.after;
let children = data.data.children;
children.map(function(val) {
let div = document.createElement('div');
div.setAttribute('class', 'card');
let img = document.createElement('img');
img.setAttribute('width', '200');
img.src = val.data.url;
div.appendChild(img);
parentElement.appendChild(div);
})
})
.catch(function(error) {
console.log(error)
});
}
}
main.js
import {
Cards
} from "./card.js";
// `<div>` Element that contains all cards.
const container = document.querySelector('.container');
// Creating all cards with class Cards.
let memeCards = new Cards('reddit', 'memes', 50);
// Binding Cards to Container.
memeCards.addCards(container);
I’m trying to fetch new images each time I click on a button. That’s the reason why I’ve created the property this.after
, but for some reason I get the error “TypeError
: Cannot read properties of undefined
(reading 'after
') at card.js:20:13”.