Recently, I've been diving into the world of Object-Oriented Programming (OOP) and trying to utilize fetch for data retrieval. Unfortunately, I've hit a snag when it comes to passing information between classes. I'm struggling to successfully pass the fetched data from one Class to another for further processing.
Sample Code
Fetch.js
class Fetch {
constructor(data) {
this.data = data;
}
async fetchData(path) {
const res = await fetch(path)
const { status } = res;
if (status < 200 || status >= 300) {
return console.log("Oh-Oh! Seite konnte nicht gefunden werden: " + status)
}
this.data = res.text();
}
}
export default Fetch;
Day08.js
1 | import Fetch from "./Fetch.js";
2 |
3 | class Day08 extends Fetch {
4 | constructor() {
5 | super(data);
6 | this.doSomething();
7 | }
8 |
9 | doSomething() {
10 | console.log(this.data)
11 | }
12 | }
13 |
14 | new Day08();
Upon checking my Console, an error message stating that data is not defined
in Day08 on line 6 appears.
Query
Therefore, my main question revolves around how to effectively use the retrieved data from the fetch operation? In an attempt to resolve this issue, I experimented with altering my doSomething()
method as shown below:
doSomething() {
const fetching = new Fetch.fetchData("./Inputs/08-data.txt");
console.log(fetching)
}
However, this also led me to encounter the same 'data is not defined' problem. Struggling to find a solution online, I'm at a loss on how to access and manipulate this data within a different class. I must mention that the input source for the fetch operation varies each time, hence my reluctance towards creating a static return in my Fetch Class. Any guidance or assistance regarding this matter would be greatly appreciated.