How can we capture the model's property value in the controller's constructor while it is being retrieved asynchronously in the MVC framework?

Implementing the MVC design pattern in my application has been a bit challenging.

I am encountering an issue where the output of this.logActivities() in the Controller's constructor is showing up as undefined. Oddly enough, I can successfully run app.logActivities() from the console after the page loads.

Could this be happening because the data hasn't been fetched yet? If so, what steps can I take to resolve this?

class Model {
         constructor() {
             this.getActivities()
                 .then(json => 
                     this.activities = json.activities
                 )
         }

         async getActivities() {
             const url = 'https://jsonplaceholder.typicode.com/todos/1'
             const response = await fetch(url)
             const json = await response.json()
             return json
         }    
     }

     class View {
         constructor() {}
     }

     class Controller {
         constructor(model, view) {
             this.model = model
             this.view = view

             this.logActivities()
         }

         logActivities() {
             console.log(this.model.activities)
         }              

     }

     app = new Controller(new Model(), new View())

Answer №1

It's showing as undefined at that point in time. Here, I present an example that displays {} to illustrate the concept.

It's up to you to figure out what to do if your fetch call never returns, like with

fetch("HTTPS://Iambadforever.gone/I/do/not/exist")

I've made a possible adjustment below

/*jshint esversion: 8 */
class Model {
  constructor() {
    this.getActivities()
      .then(json =>
        this.activities = json.activities
        //maybe try this?
        this.logActivities();
      );
  }

  async getActivities() {
    const url = 'https://jsonplaceholder.typicode.com/todos/1';
    const response = await fetch(url);
    const json = await response.json();
    return json;
  }
  
  logActivities() {
    console.log(this.activities);
  }
}

class View {
  constructor() {}
}

class Controller {
  constructor(model, view) {
    this.model = model;
    this.view = view;

    //  this.logActivities();
  }


}
let m = new Model();
console.log(m);
m.activities = {};
let v = new View();
console.log(v);
let app = new Controller(m, v);

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

Leverage Node.js/Express backend objects within frontend JavaScript

I'm new to programming and feeling a bit lost. I've been struggling to find a solution for my issue despite spending a lot of time searching. Currently, I am working on coding a prototype for a simple web app using Node.js, Express, MongoDB, and ...

The error message from Object.create() indicates that the argument provided is not recognized as

Description Within my project, I am handling a JSON file, parsing it into an object, and attempting to transform it into an instance of the ProjectFile class using Object.create(). Code let tmpFileContent = fs.readFileSync(tmpPath, {encoding: 'utf- ...

swap out the CSS class for my own class dynamically

When I display HTML code like this <div class="btn btn-pagination"> <i class="fa fa-angle-right"></i> </div> and want to replace fa fa-angle-right with myClass when the page loads. I attempted: $(document).ready(function () { ...

How can CSS and JavaScript be used to strategically position two upright images next to each other within a dynamically resizing container?

Looking for a way to display two portrait images side by side within a flexible container with 100% width? The challenge I'm facing is accommodating varying widths of the images while ensuring they are the same height. <div class="container"> ...

Encountering a 405 error when attempting to send a request through an express route in a Next

After deploying my Express js routes in Next js on hosting, I encountered an error 405 when sending requests to the route. However, everything works fine when I test it on localhost. I'm puzzled by this issue. Can anyone help me understand what' ...

The customized Vaadin component with a tag is missing from the MainView layout

I am attempting to integrate my custom vis component into the MainView VerticalLayout. However, it is appearing above the layout and the layout itself contains an empty component tag. Custom component code In this section, I have labeled my component as " ...

Guide to displaying API data in HTML format

This university assignment involves working on a homework project where I need to utilize a public API in HTML. So far, I have successfully called the public API to display a list of radio channels in the left menu (without adding any click functionality). ...

What are the reasons behind professional web designers opting for absolute paths over relative paths (like for CSS, Javascript, images, etc.)?

It used to be my belief that everyone utilized relative paths, like /styles/style.css. However, I've noticed that certain renowned web designers (such as and ) prefer absolute paths (http://example.com/styles/style.css). This begs the question - why ...

Utilizing aria-expanded="true" for modifying a CSS attribute: A simple guide

I am looking to utilize aria-expanded="true" in order to modify a css property such as an active class : <li class="active"> <a href="#3a" class="btn btn-default btn-lg" data-toggle="tab" aria-expanded="true"> <span class="networ ...

Make sure to tick off the checkboxes when another checkbox is marked

When a specific condition is met, I want my checkboxes to automatically be checked through Javascript code in MVC. @if (str_item != "" && str_checkroles != "" && str_item == str_checkroles) { <script> src = "https://ajax.googl ...

What steps can I take to avoid res.send() from replacing the entire document?

When making an ajax call to insert users into the database, I want to handle the response in a specific way. If I use res.send() on the server side, it displays the response at the top left of a black document, which is not ideal. I attempted to use retu ...

The page's scroll bar automatically moves downward as I adjust the size of the window

Exploring the world of creating a "sticky" navigation bar and menu using only the properties of "position" and "float", alongside JavaScript, has been on my agenda lately. This exercise serves as a great way to enhance my JavaScript skills. Everything see ...

Angular 6: Endlessly Scroll in Both Directions with Containers

Does anyone know of a library for angular 6 that allows for the creation of a scrollable container that can be scrolled indefinitely in both directions? The content within this container would need to be generated dynamically through code. For example, ...

Send the form via ajax

I am in the process of creating a unique application for my university, which is essentially a social network. One key feature I need to implement is the ability for users to add comments, which involves inserting a row into a specific database. To achieve ...

Discovering an arbitrary entry in Mongoose: Tips and Tricks

What is the best way to retrieve random records from MongoDB? I have come across various articles on StackOverflow discussing this topic, but I am struggling to grasp the concept. For instance: db.yourCollection.find().limit(-1).skip(yourRandomNumber).ne ...

changing the state of a bootstrap button once a task is completed

I've designed a Bootstrap 5 button to control the motor: <button id=button_90 onclick="return motor_turn(512)" class="btn btn-primary" type="button">90</button> Clicking the button highlights it in blue, and ...

Transforming a string into JSON with proper sanitization

When web scraping, the website returns a string like this on get request: jQuery18305426675335038453_1429531451051({"d":[{"__metadata":"cool"}]}) The complete code snippet is provided below: var baseUrl = "http://SOMEURL.COM?spatialFilter=nearby(52.4795 ...

Are you ready to initiate the object using setInterval?

My Sockjs reconnect method is almost fully functional, except for a small error: (function() { // Initialize the socket & handlers var connectToServer = function() { var warbleSocket = new SockJS('http://url.com:5555/warble'); w ...

Grunt and Bower are loading a single script at the top of the page

Hey there! I'm still fairly new to this, but I've been using a yeoman generator for my projects, specifically the one found at https://github.com/DaftMonk/generator-angular-fullstack. My goal is to have Angular load at the top of the index.html i ...

Tips on setting up and managing configuration and registering tasks in Grunt

I've been working on a project that involves using grunt to process my Js and SASS files. The issue I'm facing is that every time I need to make a change, I have to run all the tasks in my gruntfile.js, even if it's just for one module or th ...