Is there a way to execute v-for once the created() lifecycle hook has finished running?

In my current project, I am faced with the challenge of including avatars in notifications. Despite my efforts, I have not been able to solve this issue independently. The Vue.js template below demonstrates how I have attempted to add avatars to each notification:


    <li class="notification" v-for="(notification, index) in notifications">
        <a>
            <span class="image">
                <img :src="notification.avatar" alt="Avatar" />
            </span>

            <span class="link">
                <span v-text="notification.data.sender_name"></span>
            </span>

            <span class="message" v-text="notification.data.message"></span>
        </a>
    </li>

Below is a snippet of the accompanying JavaScript:


data() {
    return {
        user: this.initialUser,
        notifications: this.initialUser.unread_notifications,
    }
},

created() {
    let self = this;
    self.notifications = this.initialUser.unread_notifications;

    self.notifications.forEach(function(notification) {
        if(notification.data.sender_id) {
            axios.post(self.user.path + '/get-avatars', {
                id: notification.id,
            }).then((response) => {
                notification.avatar = response.data;
            });
        }
    });
},

The main issue I am encountering is that the v-for loop executes before the created() method finishes running. Consequently, the avatar property is missing from the notifications object during the iteration.

I'm seeking advice on whether there is a way to ensure that the v-for only proceeds after the completion of the created() method. Any help or suggestions would be greatly appreciated!

Thank you in advance!

Answer №1

Utilize

Invoke this.$set(notification, 'avatar', response.data)

To manually activate reactivity. It is important to have an existing avatar property for automatic reactivity when setting notification.avatar = .... If the property does not exist, use Vue's helper function.

This issue can arise with both objects and arrays.

For further details, visit https://v2.vuejs.org/v2/guide/reactivity.html

Answer №2

It seems unnecessary to delay the execution of the v-for directive in this scenario. Simply ensure that the notification object contains the avatar field, even if it is set to undefined. This can be achieved by modifying the parent element or using a computed property that assigns the avatar field to incoming objects:

this.initialUser.unread_notifications.map(notification => Object.assign({ avatar: undefined },  notification)

If you prefer not to render a notification until the avatar is loaded, consider the following options:

  1. Include v-if="!!notification.avatar" within the li element (Note: The Vue linter may discourage this approach, but some find it convenient as it filters output based on a condition).
  2. Create a computed property such as
    unread_notifications_with_avatars
    , defined as
    this.initialUsers.unread_notifications.filter(notification => !!notification.avatar)
    , and use this property with your v-for directive.

If you really need to wait for all avatar calls to complete before rendering the list, there are methods to achieve this (e.g. using

Promise.all(...).then(() => this.showTheList = true)
). However, it appears that this level of complexity may not be necessary in your current situation.

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

Changing the order of elements in a JavaScript array

Issue: Develop a function that accepts an array as input and outputs a new array where the first and last elements are switched. The initial array will always be at least 2 elements long (for example, [1,5,10,-2] should result in [-2,5,10,1]). Here is ...

No children were located within the div element

Presently, I am attempting to disable an image for the initial element in each faqs div class in HTML. To achieve this, I am aiming to target the parent element of faqs and then navigate downwards to locate the initial list element using the following Java ...

Difficulty with Horizontal Mousewheel Scrolling

Struggling to implement a horizontal scrolling feature (via mousewheel) for both containers in the code below. I want this feature to be easily applied to any future container creations as well. <body> <style> #container { display: flex ...

Error message: The 'node_modules' directory is not found after installing

During class today, I faced a problem. I was demonstrating to my students how to install and use gulp.js using a projector. I successfully installed node.js and gulp.js globally with npm install -g gulp without any issues. However, when attempting to ins ...

When the visitor is browsing a particular page and comes across a div element, carry out a specific action

I am trying to determine if I am currently on a specific page and, if so, check if a certain div exists in that page. Here is what I know: To check if a specific page exists, I can use the code if('http://'+location.hostname+location.pathname+& ...

Why is it that my for loop produces the accurate result, yet my forEach function fails to do so?

Hey there, I'm new to SO and seeking some guidance. I have a task where I need to create a function with two parameters - an array of strings and a string to potentially match within the array. I've developed two versions of the function: one us ...

How can you preselect an item in Vuetify's item group?

When attempting to preselect an item from a vuetify item-group, I discovered that it works with strings but not with objects. The vuetify documentation shows using a string array as the item list for the item-group, which functions correctly. However, whe ...

Steps to display a variable in JavaScript on an HTML textarea

I'm working on a JavaScript variable called 'signature' var signature; //(Data is here) document.write(signature) Within my HTML document, I have the following: <div id="siggen"> <textarea id="content" cols="80" rows="10">& ...

Nodemailer fails to display an error message when the email is not successfully sent

I am currently working on implementing nodemailer for sending emails. However, I noticed that if the email address in the "to" field is incorrect, the email is not sent as expected. The issue is that there is no error displayed and the function still resol ...

Using JQuery AJAX to successfully retrieve data and then smoothly applying the fadeIn

Utilizing AJAX, I am loading survey content into a container on a webpage. As part of the transition, I have implemented a fadeOut effect on the container, followed by fadeIn once the content is loaded. This method functions correctly for pages 1-4; howeve ...

Combining arrays of objects in JavaScript

I am currently working on combining different arrays: const info1 = {id: 1} const info2 = {id: 2} const info3 = {id: 3} const array1 = [info1, info2] const array2 = [info1, info3] const array3 = [info2, info3] const union = [...new Set([...array1, ...arr ...

A method for displaying data within a loop based on a condition in Vue.js/Nuxt.js

I am seeking assistance in Vue.js/Nuxt.js to display a column of checkboxes using an image as reference. My goal is to use a for loop to display all the checkbox data, with 3 items in each column. <div class="row"> <div class="col-xxs-6 co ...

A Node.js function may not provide a response immediately due to a pending request

Here is a simple upload method using node.js and express.js: upload: function(req, res, next){ // Loop through each uploaded file async.each(req.files.upload, function(file, cb) { async.auto({ // Create new path and unique file ...

What is the best way to transfer data from MongoDB (utilizing the Mongous module) to a Node.js view (using the Jade templating

Hello everyone, I have a quick question regarding passing data from a model (database) into a view. I am using Express, Mongous (not Mongoose) to access MongoDB, and Jade for my views. Despite trying to use Mongoose, I have not been successful in achieving ...

Making changes to an AngularJS property updates the value of an HTML attribute

One of my pages, base.html, contains the following code: <html lang="en" data-ng-app="MyApp" data-ng-controller="MyController"> <body style="background-color: [[ BackgroundPrimaryColor ]]"> . . . {{ block ...

Creating a 3D object using three.js framework

When playing video games, I often notice a common pattern where hovering the mouse over an object triggers a gradient highlight around its 2D representation. To recreate this effect in my Three.js scene, I started by setting up the necessary raycaster vari ...

Discrepancy in post results

I am currently working on integrating two scripts - a Prestashop DHL label creator and our company's internal sales application. The goal is to streamline the process of generating DHL labels directly from our sales application without the need to acc ...

Creating a quiz with just one question in React: A step-by-step guide

How can I add the functionality to handle correct and incorrect answers? I've designed a single-question quiz with multiple options. The Quiz component has been created. See the code snippet below: Quiz Component export default function Quiz(props) { ...

use vue.js to change the color based on a condition

When I implement this code: <div class="card-content"> <vue-tabs class="row" direction="vertical" value="Description"> <div v-for="(item, index) in siteObject.line_info" :key="index"> <v-tab :title=" ...

Exploring CryptoJS in a Vue.js project

https://github.com/brix/crypto-js I successfully installed CryptoJS using npm i crypto-js. However, I am facing difficulty in integrating it into my project. When I attempt to use the following code: // Decrypt var bytes = CryptoJS.AES.decrypt(cipher ...