Tips for implementing fetch in object-oriented programming

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.

Answer №1

To ensure that the data fetched from the Fetch class can be accessed in other classes, it is important to note that since the fetchData call is async, any code utilizing the data must be placed after the async call has completed in an asynchronous manner.

class Fetch {
  async fetchData(path) {
    const res = await fetch(path)

    const {
      status
    } = res;

    if (status < 200 || status >= 300) {
      return console.log("Uh-Oh! Page could not be found: " + status)
    }

    this.data = await res.text();
  }
}

class Day08 extends Fetch {
  constructor(path) {
    super()
    this.path = path;
  }

  async init() {
    await this.fetchData(this.path);
  }

  doSomething() {
    console.log('Doing something', this.data)
  }

  doSomethingElse() {
    console.log('Doing something else', this.data)
  }
}

const day = new Day08('https://jsonplaceholder.typicode.com/todos/1')

day.init().then(() => {
  day.doSomething();
  day.doSomethingElse();
})

Answer №2

It appears that the issue lies in the fact that the constructor of Day08 requires a data parameter

constructor(data) {
   super(data);
   this.performAction();
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having difficulty maintaining trailing zeroes in decimals after converting to float in Angular

I need assistance with converting a string to float in Angular. Whenever I use parseFloat, it seems to remove the zeros from the decimal values. How can I ensure that these zeros are retained with the numerical values? The example below should provide more ...

Utilize the ionicPlatform.ready() method for implementing a service factory

Within my app.js file, I have the following method: .run(function($ionicPlatform) { $ionicPlatform.ready(function() { gvi.Notifications.registerForPush(MessagesService.onNotificationResponse); }); }) Additionally, I have a factory ...

Having trouble locating a module in Angular2 and SystemJS while constructing a module loader

What's the Situation Here? Currently, I'm immersed in a project that involves SystemJS, Angular2, and @ngrx/store. My current focus is on developing a basic module loader. Here's how it works: I create a "module" in its own folder, named ...

Struggling with synchronicity in javascript(node.js) and seeking assistance

I am faced with a challenge in my express.js app where I need to execute a script on the server, followed by running a couple of functions to derive some values. The process should be sequential, but I am running into issues as JavaScript seems to move on ...

The method being spied on by Sinon has not been called

Testing the code involves a simple process: it triggers a method based on a certain condition. If the condition is not met, another method from within the first one is triggered as an attribute. app.js: function test (fn, isActivated) { if (isActivat ...

The start-up process of AngularJS applications with Bootstrap

Curious about the predictability of the initialization flow in AngularJS apps? Want to understand the order of execution of different blocks within an HTML document? I came across a question on bootstrapping in Angular JS, but it didn't delve into th ...

Understanding the status of HTTP requests or observing the updates of observables in Angular2/Typescript is essential

I've been working on an Angular2 and Typescript application where I'm utilizing Angular2's HTTP methods to retrieve data from a database within a service. The service is triggered inside a component's onInit() function and I'm able ...

Show the comment section only if the initial radio button is selected

I am struggling to implement a comment section that is displayed when the first radio button is checked. Here's the code I have tried: I attempted the following to show the section and test the associated script: <div id="commentaryDiv" ...

Incorporate formdata append into your @HTML.BeginForm without the need for an ajax request

I am attempting to append a file to a post request that I received from a drag & drop field using JavaScript. The challenge is that I do not want to manually read all input fields and post the data via an ajax call, but rather utilize the default submit me ...

Creating an overlay with CSS hover on a separate element and the ::before pseudo class

Issue: I am struggling to display the overlay when hovering over the circle element, rather than just the image itself. I have attempted to achieve this using CSS, but can't seem to make it work as intended. Any guidance and examples using JavaScript ...

Rendering JSON data in a dropdown menu

When I select an option, all the data is being combined into one row. I want the data to fill each row based on the select option. Any suggestions on what code I should modify or add? Is it related to the loop or should I create a dynamic id for the selec ...

Is anyone else experiencing issues with loading a font from a CDN? It works perfectly fine on Chrome Browser and Safari for iOS Simulator, but for some reason, it's not loading

It's driving me a bit crazy as I'm not sure where I've gone wrong. I'm currently working with NextJS and have loaded this font into my <Link />. While it displays perfectly on Chrome and Safari in the iOS simulator, it fails to l ...

The issue of Next.js 13.4 fetching failing to work properly in a production environment

In development mode, everything runs smoothly. However, when I switch to production and create a new row in Prisma, the API only returns old rows that were present before running npm build. What could be causing this issue, and how can it be resolved? Fro ...

Animate a nested element dynamically with jQuery

Whenever I click on the "view" button, I am dynamically adding data to a div. This feature is working perfectly fine. However, I wanted to improve it by adding another nested dynamic element. The problem I'm facing now is that when I try to expand al ...

Conditional jQuery actions based on the selected radio button - utilizing if/else statements

This task seemed simple at first, but I quickly realized it's more challenging than expected. Apologies in advance, as Javascript is not my strong suit. My goal is to have the main button (Get Your New Rate) perform different actions based on whether ...

Unforeseen issue within Vuejs-nuxt (SSR Mode) is preventing the retrieval of the UserUUID through the getter in plugins, resulting in an unexpected '

In my vuejs-nuxt project using SSR mode, I encountered an issue when trying to call a socket event. I need to pass the userID to the socket from the store. The GetUserUUID getter functions properly in all other APIs except when called from the "plugin/sock ...

Guide to configuring a robust schema and validation with joi

Currently in the process of setting up validation using the joi package, encountering syntax-related issues along the way. The schema in place is simple, checking for a valid number and verifying if the ID exists in the database. export default router.pos ...

How can I transfer information from Node.js to Vue in an Nuxt.js server-side rendering setup?

I need to find a way to pass Firestore data to Vue files from Node.js (Express) because I have to utilize Firestore's getCollections() method, which cannot be executed on the client side. I have set up nuxt-ssr for deploying Google Cloud Functions an ...

Utilize jQuery to trigger video playback based on the horizontal movement of the mouse

Utilizing this jQuery script to navigate back and forth in a video as the cursor moves along the x-axis. var mouseX; $(document).mousemove( function moveFunc(e) { mouseX = e.clientX; var timV = $("#deko_vid").get(0).duration; var valV = (timV*mouseX/$(do ...

A tutorial on creating circular patterns within a pyramid structure using p5.js and matter.js

I've been attempting to create a pyramid shape using multiple circles, similar to this: balls in pyramid shape To achieve this, I've developed a 'Balls' class: class Balls { constructor(x, y, radius, color, ballCount) { this.x = ...