What is the process of transferring fetched data to a different module?

I am facing a situation with two modules, module.js and controller.js. In the module file, I have the following code:

export class Module {
    constructor(){
        const fetchParams = {
            method: "GET",
            mode: "cors",
            cache: "default"
        };
        const url = 'https://swapi.co/api/people/';
         fetch(url, fetchParams)
            .then(res => {
                if(!res.ok){
                    throw new Error(res.statusText);
                }
                return res.json();
            })
            .then(data => {
                const characters = data.results;
                this.characters = characters;
            })
    }
}

As for the controller file, it looks like this:

import {Module} from "./module";
class Controller extends Module{
    constructor(){
        super();
    }

    checkData(){
           console.log(this.characters);
    }
}

When running checkData(), I encounter an issue where the result is undefined. How can I ensure that I wait for the response from the module before accessing the data in checkData()? PS: I am utilizing webpack.

Answer â„–1

If you want to improve the readability of your code in Module, consider moving the fetch call to a separate method. This way, the child class can simply call that method and attach a .then to the promise for handling errors and waiting for its completion. For a cleaner code structure, explore using async/await syntax by referring to this guide.

class Module {
  constructor() {
    this.characters = []
  }

  fetchCharacters() {
    const fetchParams = {
      method: "GET",
      mode: "cors",
      cache: "default",
    }

    const url = "https://swapi.co/api/people/"

    // It is crucial to return the promise from fetch to allow callers to use it
    return fetch(url, fetchParams)
      .then(res => {
        if (!res.ok) {
          throw new Error(res.statusText)
        }
        return res.json()
      })
      .then(data => {
        const characters = data.results
        this.characters = characters
      })
  }
}

class Controller extends Module {
  checkData() {
    return this.fetchCharacters().then(() => {
      console.log(this.characters)
    })
  }
}

new Controller().checkData()

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

Issue with submitting forms in modal using Bootstrap

In the model box below, I am using it for login. When I click on either button, the page just reloads itself. Upon checking in Firebug, I found something like this: localhost\index.php?submit=Login <div class="modal fade" id="loginModal" tabindex= ...

JavaScript causes the browser to freeze

When I execute this code, the browser freezes and I'm not sure how to troubleshoot it, can you assist? http://jsfiddle.net/z3DjY/1/ var levelArray = new Array(); var canvas; var ctx; var playerLocation; var edge; var elementEdge = 10; // Each elemen ...

JavaScript array object alerts as empty

Having an issue sending a JavaScript array to my PHP as it appears to be empty []. This is not the usual JSON format that I have worked with in the past. Here is an example code snippet: var blah = []; var letters = ['a', 'b', &ap ...

Are there any alternative methods for clearing form fields following a successful thunk dispatch in React?

When implementing a Post API call in Thunk, I dispatch a boolean success key for successful requests and an error message for errors. Now the goal is to clear form data upon success and display the error message upon an error. To achieve this, I utilize ...

The Angular template driven forms are flagging as invalid despite the regExp being a match

My input looks like this: <div class="form-group"> <label for="power">Hero Power</label> <input [(ngModel)]="model.powerNumber" name="powerNumber" type="text" class="form-control" pattern="^[0-9]+$"id= ...

Placing a function within an array raises the question: why is the array's value represented as an integer?

There's something puzzling happening in my code. I've placed a setTimeout function inside an array, but when I check the contents of the array using console.log(arr), it only shows an integer value. How is this possible? See the code snippet belo ...

Does Chrome have a feature that disables event listeners?

I'm currently working on a tool that incorporates file drag and drop functionality. Strangely, this feature works perfectly in all browsers except for Chrome. Surprisingly, however, it does work in Chrome when the tool is run locally. Here is the cod ...

The Socket.io authorization feature is failing to refresh session information

I am currently working on implementing Socket.IO's authorization function to retrieve session data. However, I have encountered an issue where even after logging out and destroying the session, Socket.IO retains the old session information, which is l ...

What is the best way to ensure a jQuery UI slider recognizes when the mouse is released after being clicked?

I have integrated the jQuery slider into my application and am facing an issue with triggering an event to update the database upon releasing the slider. Currently, I am using the following code snippet: $('.ui-slider-handle').mouseup(function () ...

Tips for installing npm packages using a python script in the same directory as my script

The desired file structure should resemble this: test.py node_modules (Folder containing installed npm modules) Here is the attempted solution: import subprocess import os dir_path = os.path.dirname(os.path.realpath(__file__)) # Retrieve the directory ...

Sending a file using Angular's $http service

I am facing an issue while trying to upload a form with an image file using the angular $http function and multer in the background for receiving. I have successfully uploaded the image via a direct form submission (without angular) as shown below: <fo ...

How can I access a PHP variable from an external .php file within a JavaScript script?

I have recently implemented a JavaScript code called "upload.js" for uploading files to my server: function beginUpload(){ document.getElementById('upload_form').style.visibility = 'hidden'; return true; } function endUpload(s ...

When attempting to retry in Next.js, the props obtained from getServerSideProps may

Currently, I am facing an issue with sending axios requests in getServerSideProps and passing the value through props via SSR to the client. The challenge lies in including a token in the header using an instance. In case the token expires, I utilize refre ...

Issues with sending data using ajax

Trying to get weinre working through Ajax by calling this on dom ready: $.ajax({ url: 'http://debug.build.phonegap.com/target/target-script-min.js#hutber', dataType: "script", crossDomain: true, error: function(data){ c( ...

The request body is not defined within the Express controller

Currently facing an issue with my controller: when I use console.log(req), I can see all the content of the request body. However, when I try console.log(req.body), it returns as undefined. This problem arises while working on my Portfolio project with Nex ...

Implement a jQuery loop that utilizes the fadeIn effect

Currently, I have a basic jQuery function in place to generate a small image slider: function gridhover() { $(".grid-item .slide-image").each(function(index) { $(this).delay(400*index).fadeIn(300); }); } $( ".grid-item" ).hover(function() ...

Incorporating live reload functionality with connect-livereload in an Express Node.js

After reading a helpful article on utilizing npm as a build tool for Node.js, I am eager to implement it in the development of my express web app. My server.js file is set up to run the node application on port 8080 with the following configuration: var e ...

ng-options do not refresh automatically when modifying elements in the array

Having trouble updating the data in a select list? It seems that when selecting 'test', the value retrieved from the API is 'ÅšlÄ…sk' even though it's not listed. For example: I select 'test' but it shows as 'ÅšlÄ ...

Angular 7 - Implementing periodic JSON data retrieval from server and maintaining local storage within Angular application

Seeking guidance on how to handle updating a static json file stored in the assets directory in an Angular 7 project. The goal is to periodically fetch a json from a server, check for updates, and perform post-processing on the data in the static file (ess ...

Enhance your React application by using a personalized hook that allows you to trigger a function

After creating a custom hook to handle uploads to an AWS S3 bucket, I encountered a small issue. Rather than having the hook execute the logic directly, I decided to create an executable function to return instead. However, I am facing a problem where the ...