Issues encountered while manipulating an array in a Vue prop with Filter, forEach, and Push methods

I am attempting a relatively simple task. The parent component passes an ID as a prop to the child component, which then tries to filter the "topics" array to only return the topic with the same ID.

However, filtering this array is proving futile. Even using this.topics.filter(x => x); results in an empty array.

The line

this.topics.forEach(x => console.log('working!')
does not log anything either.

this.topics.push("Some new Element")
resets the array completely and includes only "Some new Element."

console.log(this.topics) displays the full array, except when using the push method - in that case, it shows only the "new" Array with the pushed element.

No errors are thrown in the console. The array is not empty; Firestore populates it without issues (refer to the screenshot below).

To investigate if there was an error within the file, I attempted creating another array in the data() function containing only strings. Filtering "normal" arrays works perfectly fine.

this.topics consists solely of objects – could this be the cause?

Filling the topics array in the created hook by fetching data from Firebase works flawlessly (Check out the screenshot below for confirmation)

    db.collection("courses").doc(this.$route.params.course_id).collection("sections")
    .get()
    .then(snapshot => {
      snapshot.forEach(sec => {
        if (this.topics.length == 0) {
          db.collection("courses").doc(this.$route.params.course_id).collection("sections").doc(sec.id).collection("topics").orderBy("order")
            .get()
            .then(snapshot => {
              snapshot.forEach(doc => {



              // Magic starts here.
                this.topics.push({
                  data: doc.data(), 
                  topic_id: doc.id,
                  sectionOfTopic_id: sec.id
                
              // And ends here




                })
              })
            })
        } else {
          return;
        }
      })
    })

The data() function:

  data() {
    return {
      courseTitle: null,
      sections: [],
      topics: [],
      selected: undefined
    }
  }

Efforts to filter the array in the mounted hook (also tried in methods and created hook)

  mounted() {
    
    console.log(this.topics)
    let preview = this.topics.filter(x => x)
    console.log(this.topics)
    console.log(preview)
}

When using this.topics.filter(x => x), one would expect a direct copy of the array, but it returns an empty array [].

https://i.sstatic.net/akyOc.png

Answer №1

Finally, after spending some time troubleshooting, I managed to get the code working as expected. Big shoutout to @TylerRoper for pointing out that the issue was related to the code running asynchronously. Initially, I mistakenly assumed that Vue lifecycle hooks handled asynchronous operations, but it turns out that is not the case.

The solution involved adding watch properties:

  watch: {
topics: function (val) {
  this.topReady = true;
  if(this.topReady && this.secReady){
    this.allReady = true
  }
},
sections: function (val) {
  this.secReady = true;
  if(this.topReady && this.secReady){
    this.allReady = true
  }
},
allReady: function (val) {
  return this.loadPreview()
}

Additionally, I updated the data structure accordingly:

  data() {
return {
  courseTitle: null,
  sections: [],
  topics: [],
  selected: undefined,
  topReady: false,
  secReady: false,
  allReady: false
}

Furthermore, I organized the actions within a method triggered by one of the watch properties:

    loadPreview() {
  // Set previewSpecs
  let preview = this.topics.filter(top => this.previewSpecs.topic_id==top.topic_id)
  let previewSotId = preview[0].sectionOfTopic_id
  let previewSec = this.sections.filter(sec => sec.section_id==previewSotId);


  this.selected = previewSotId;
  this.choose(preview[0].topic_id, false, preview[0].sectionOfTopic_id, previewSec[0].data.name)
}

Everything is now functioning correctly. Huge thanks to everyone who assisted me in resolving my first question on Stack Overflow!

If there's a more efficient way to tackle this problem, I'm open to hearing your suggestions.

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

Sort posts alphabetically by their first letter using jQuery

Currently, I am dealing with a collection of products sourced from WooCommerce and displayed as custom posts through the Elementor page builder at this link: My attempt to incorporate an alphabetical filter using a plugin has not been successful, most lik ...

Event handler for jQuery AJAX signals

Let's say I have an object called myApi which has a function named execute var api = new myApi(); api.execute(); Within the execute method, I have (*that referring to the myApi instance) function execute() { $.ajax({ type: t ...

Access data through Twig for loop from an array to retrieve the value

Here is the structure of my array: 'contents' => array( 'row' => array( 'col-xs-6' => 'grid 1', 'col-xs-6' => 'grid 2' ...

Stop Kendo Grid from refreshing while a filter is in use

I am facing a challenge with my javascript function that automatically refreshes the Kendo Grid every 5 seconds. I need to find a way to prevent this functionality from running when the Filter dialog is open or filtering is active. Is there a solution fo ...

Is it necessary for React components to be organized in a hierarchy?

In all my years, I've been told that React components should follow a tree hierarchy so that parent components can manage state and pass it down to their children. But is this truly necessary? The guiding principle of React states that "React has bee ...

Easy method for importing videos into NextJs

Import Coding Guidelines Encountering an error after importing the code, unable to find any solutions online ...

The function for the "load next page" action in ngInfiniteScroll is continuously triggered

After attempting to implement infinite scrolling using the "loading remote data" example from the ngInfiniteScroll website, I am facing a problem. The function nextPage() is being called continuously until all records have been loaded (controlled by an of ...

Utilizing useEffect to retrieve and display an empty array in a React component

I am currently developing a React application that leverages Fetch to retrieve data from an API using SQLite. Strangely, when I check the console, it only displays a length of 3 and Array[0]. This means I can't access data based on specific IDs like I ...

Creating POST requests using the FormData API

I am trying to pass the username and form_data object to a PHP file using http.post. When I only pass form_data, my picture upload works fine. However, I also want to pass some other information like the username. Can someone please help me with how to p ...

Tips for transitioning from Angular to Angular 2: Overcoming key challenges

Our current Angular project is highly developed, but with the emergence of Angular 2 and its advanced features and improved performance, we are considering migrating our existing work. However, we are concerned about the potential challenges that may ari ...

Adjusting the size of several images individually with jquery

Currently, I am working on a jQuery script that enables me to resize any image by simply clicking on it. The goal is to have the ability to click on one image and resize it, then click on another image and resize it independently. Here is the code I have b ...

Retrieving information selectively using useSWRImmutable

Having issues fetching data using useSWRImmutable. The problem arises when attempting to display the fetched data inside the UserRow component. Even though I can successfully print the data outside of the UserRow component, any console.log() statements wi ...

Manipulating SVG image color using JavaScript

Is there a way to change the colors of an svg image using Javascript? Perhaps by loading it as an object and accessing the color/image data? I would greatly appreciate any responses or tips on this matter! ...

Processing JSON data by reading multiple files using Node.js

I've encountered a situation where I have multiple files containing data with time stamps. It's important for me to read these files in order, line by line. However, I noticed that most Node packages utilize asynchronous methods for file reading. ...

The specified package, [email protected], fails to meet the peerDependencies criteria set by its sibling modules

Encountering errors when attempting to run npm install. I'm puzzled why it's not working despite using the most recent version of React. npm ERR! peerinvalid The package <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail ...

PHP Combining two arrays by adding an element to each existing element

How can I merge elements from one array with each element in another array? For instance: $colors = array("black", "white", "yellow"); $numbers = array("1", "2", "3"); I am looking to create a new array that combines them all like so: $colornumber = a ...

Displaying an array with no elements assigned to it

I am facing an issue with React. I have been using the fetch API as per a tutorial to retrieve data from my API and display it in React. Here is the JSON data I am working with: { "Configuration": [ { "id_configuration": 1, "language": "E ...

Exporting and importing modules in Angular 1 using Webpack 2

Seeking clarification on why the current implementation is not working as expected. It seems like a simple oversight, especially since it works fine without Webpack. I prefer to stick with the current implementation, where each component/controller/etc is ...

Is there a versatile Node.js HTTP request module that is compatible with both server-side and browser-side development, particularly when packaged with Webpack?

Currently, I am searching for a request module that can operate seamlessly in both the Node.js server and the client when compiled with Webpack. The requirements are quite straightforward. I simply need to execute some basic HTTP Ajax requests such as get ...

Establish the Central European Time (CET) timezone using the toISOString

Has anyone figured out how to convert a MYSQL timestamp date to a JS date using toISOString() and adjusting the time-zone to CET? I have been trying to achieve this with the following code, which currently produces the format "2021-02-251 15:27:20" - howev ...