The object's key values were unexpectedly empty despite containing data

There's an issue with my object - it initially gets key values, but then suddenly loses them all.

All the key values become empty and a message appears in the console for the object: "this value was evaluated upon first expanding. it may have changed since then", even though I haven't changed its value elsewhere.

This is what my service looks like:

image = {
  name: "",
  path: "",
  data: ""
};

async loadFileData(fileNames: string[]) {
    for (let f of fileNames) {
      const filePath = `${IMAGE_DIR}/${f}`;
      const readFile = await Filesystem.readFile({
        directory: Directory.Data,
        path: filePath
      });

      this.images.push({
        name: f,
        path: filePath,
        data: `data:image/jpeg;base64,${readFile.data}`
      });

      // testing
      this.image.name = f;
      this.image.path = filePath;
      this.image.data = `data:image/jpeg;base64,${readFile.data}`;
    }

    console.log('my image: ', this.image);
  }

  async loadFiles() {
    this.images = [];

    const loading = await this.loadingController.create({
      message: 'loading data...',
    });
    await loading.present();

    Filesystem.readdir({
      directory: Directory.Data,
      path: IMAGE_DIR
    }).then(result => {
      this.loadFileData(result.files);
    }, async err => {
      console.log('err: ', err);
      await Filesystem.mkdir({
        directory: Directory.Data,
        path: IMAGE_DIR
      });
    }).then(_ => {
      loading.dismiss();
    });
  }

This is how my component is set up:

this.photoService.loadFiles();

console.log('my object: ', this.photoService.image);

console.log('is my object empty? ', JSON.stringify(this.photoService.image) === '{}');

Here's a screenshot from my console

Answer №1

The initial value was

image = { name: "", path: "", data: ""};
. Later, you modified it to look like
{ name: "164....", path: "stored...", data: "data..."};

I can create a similar demonstration in the console: https://i.stack.imgur.com/O6S9U.png

What happens when I click the expand button? https://i.stack.imgur.com/DebpM.png
Now, it displays that the data has been changed to "whatever", but the original value

image = { name: "", path: "", data: ""};
is still logged.

The expanded version shows the updated data. The empty values belonged to the previous data.

Answer №2

Exploring asynchronous behavior and memory management in JavaScript.

Executing

console.log(this.photoService.image)

this.photoService.loadFiles(); is triggered

The current value of this:

{ name: "", path: "", data: ""}

Upon inspecting the console:

this.photoService.loadFiles(); completed

Memory allocation for this.photoService.image has been updated

This results in:

{ name: "xxx....", path: "yyy...", data: "zzz..."}

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

An error has occurred in the Shadow Dom due to the inability to access the property 'style' of an

While working on a component using shadow DOM, I encountered the following error in the console: "Cannot read property 'style' of undefined". This issue seems to be related to my HTML code in PHP. The main challenge I am facing is figuring out ho ...

Javascript selection menu

<body> <script> window.open("http://yourdomain.com:12345/custom/script","_parent"); document.getElementById("dropdown").selectedIndex="2"; </script> </body> Hello, can someone help me troubleshoot my code? My intention is to open ...

I'm perplexed by setting up Node.js in order to work with Angular.js

Currently following the Angular tutorial provided at https://docs.angularjs.org/tutorial, but I'm encountering confusion with the Node.js installation. Having already installed node globally on my Mac, the tutorial mentions: The tutorial instructio ...

Updating the regex pattern for the date format to dd-M-yy in jQuery Validation Engine

Snippet for validating date format using JavaScript: "date": { // Custom function to check if date is valid with leap year consideration "func": function (field) { //var pattern = ne ...

What is the solution to adding values from a counter?

I am trying to create a JavaScript counter: function animateSun() { var $elie = $("#sun"); $({ degree: 0 }).animate({ degree: 360 }, { duration: 190999, easing: 'linear', step: function(val) { now = Math.round ...

obtain a Javascript variable within a Jade template by using inline code

script. var hide_section = 'block'; .title(style='display:#{hide_section}') I received an undefined value, any thoughts on why? Could it be because #{hide_section} is trying to access a variable from the back-end, such as the cont ...

Nodejs functions properly on a local machine, however, it encounters issues when deployed on a VPS

My nodejs/javascript code seems to be running fine on my local pc, but when I try to run it on my vps, it's not working properly. Even though I have the same node_modules installed and the code is identical. Here's a snippet of my code for refere ...

Email the jQuery variable to a recipient

I'm facing an issue with sending a jQuery variable containing HTML and form values via email using a separate PHP file with the @mail function. My attempt involves using the jQuery $.ajax function on form submit to send this variable, but unfortunate ...

Using Vue.js to process JSON data

My issue lies within this JSON data. I am trying to consume only the first element of the array using Vue.js 2 in order to display it. I was able to achieve this successfully using the console, but not with Vue.js. This line of code in the console works: ...

Having trouble connecting v-model to vue-date-picker

My experience with the vue-date-picker and v-model for two-way data binding has been interesting. Initially, I set the value to a date (referred as startDate in this case) and printed the passed value (i.e. startDate) in the console. The initial value pa ...

My program contains redundant sections that are being repeated multiple times, and I am unsure of how to remedy this issue

This particular payment gateway relies on a paid market for processing transactions. Unfortunately, there seems to be an issue where multiple error messages are being triggered during the payment verification process. The errors include: ❌ | An error h ...

Issue with redirect after submitting CakePHP form not functioning as expected

I am in the process of developing a button that will submit a form and then redirect to another page. $('#saveApp').click(function() { event.preventDefault(); $("form[id='CustomerSaveForm']").submit(); // using the nati ...

Having issues with my toggler functionality. I attempted to place the JavaScript CDN both at the top and bottom of the code, but unfortunately, it is still not

I recently attempted to place the JavaScript CDN at the top of my code, but unfortunately, it did not have the desired effect. My intention was to make the navigation bar on my website responsive and I utilized a toggler in the process. While the navbar di ...

Looking for an alternative to document.querySelectorAll?

My issue involves using querySelectorAll('a') to select all buttons, but I only want to target two specific buttons labeled 'Know More'. How can I achieve this? Below is the code snippet in question: const buttons = document.query ...

I am experiencing issues with arrow pagination not functioning properly in TypeScript

My current project involves building a customer table with 10 customers displayed on each page. Additionally, there are arrows below the table to help users navigate and view more customers. Unfortunately, there seems to be an issue with the functionality ...

"Fetching and Utilizing the Output Parameter from an API in Angular4: A Step-by-Step Guide

Working on a post method in an Angular 4 web app, I am able to save data to the database successfully. However, I am facing an issue where an ID (return value) is passed from the DB to the API for Angular as another function parameter. How can I retrieve t ...

Puppeteer gathers data on page loading - including a comprehensive list of files loaded and their respective sizes

Is it feasible to compile a complete list of all files loaded on a webpage using Google's Puppeteer? This would include scripts, styles (excluding inline), images, videos, and audio, along with their respective sizes. If Puppeteer cannot provide this ...

What is the best way to send an HTTP request in AngularJS to receive data in JSON format?

I am trying to create an AngularJS app that can send HTTP requests for JSON data. I have written the code in my index.html file to request JSON data using AngularJS, but for some reason, the JSON data is not being printed. When I check the console in Fire ...

Tips for retrieving document body from a script embedded within document.write

I urgently need assistance! I am currently developing an application that retrieves a report from an API, and the JSON response includes HTML content. Unfortunately, due to the JSON format, I cannot directly open this in a new browser window. Within my sc ...

Avoiding the selection of HTML canvas objects

I am currently working on customizing my homepage with an interactive animation. However, I am facing some challenges in integrating it seamlessly into the page. You can view the progress at . My main issue is preventing the canvas object from being select ...