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

Access the id of an object in an array using Vue.js

Is there a way to showcase value data depending on the index array? I have created a modal for editing data, with a JSON structure like this: [ { "ID": 3, "idusers": 3, "skills": "Go", ...

Error: Node application using Express does not display 'Server Started' message in console upon execution

I'm encountering an issue where I don't see the "Server Start: 3001" message on the console when I run 'node app.js' in the terminal. Below is the content of my app.js file: var createError = require('http-errors'); var exp ...

Updating the parent page host within a cross-domain iframe: issues encountered in Firefox and Chrome browsers

I am encountering an issue with my iframe app where I am receiving an alert indicating "-error" in Chrome related to top.location.href. jQuery.ajax({ type : 'get', url : 'check_if_fb_data_set.php', success ...

What is the best approach to breaking down attributes upon import according to the theme?

Hey there! Here's the thing - I have this file called <code>colors.ts:

export const black = '#0C0C0C'; export const blue = '#22618E'; Whenever I need to use a color, I import it like so: import {black} from 'Shared& ...

Can you explain the variances between the index.html and index-async.html files within the AngularJS seed project?

Within the angularjs seed project, there are two files that appear to produce identical results: index.html and index-async.html. If you want to view the code for index-async.html, you can visit this link. Similarly, if you're interested in the code ...

Tips for transforming code with the use of the then block in javascript, react, and cypress

In my code snippet below, I have several nested 'then' clauses. This code is used to test my JavaScript and React code with Cypress. { export const waitForItems = (retries, nrItems) => { cy.apiGetItems().then(items => { if(items ...

What methods are available to verify all my (JavaScript) AJAX calls when they are being sent to Node.js?

My web app sends hundreds of HTTP requests to a Node.js API I created. I need to ensure that only authenticated requests are accepted by Node.js. The issue at hand: I don't want to manually update each AJAX request in my JavaScript code to include a ...

Altering the hue of various stroke patterns

I've encountered an issue where I want to create skill bars that display my skills in percentages. Luckily, I found a great code that allows me to do this. Although I would prefer to do it myself, I haven't come across a good tutorial that teache ...

Struggle with registering fonts in Canvas using JavaScript

I've been struggling to add a custom font to my canvas for hosting the bot. Even though I'm not encountering any errors, the font fails to display on the host. Below is the code snippet: const { AttachmentBuilder } = require('discord.js&apos ...

The express post request body fails to appear, rendering it empty

Server Side Code const express = require('express'); const app = express(); app.use(express.json()); app.use(express.urlencoded({ extended:true })); app.post('/',(req,res)=>{ console.log(req.body) }) Client Side Code const da ...

Scroll to make the div slide in from the bottom

I'm trying to achieve a similar effect like the one shown in this website (you need to scroll down a bit to see the divs sliding in). Although I'm not very proficient in JS, I was able to create a code that makes the divs fade in from 0 opacity ...

Interactive calendar using Php and Javascript/Ajax

Currently, I am working on a PHP calendar and have integrated Javascript/Ajax functionality to enable smooth scrolling between months without the need for page refresh. Interestingly, the calendar displayed as expected before implementing Javascript/Ajax, ...

Tips for effectively managing asynchronous tasks

I keep getting different numbers every time my code runs. Can you tell me if I'm doing this the right way? Here's the code: export class GetPlanetsService { url='https://swapi.co/api/planets/?page='; planets:Planet[]=[]; headers: ...

Having difficulty placing a marker using google-maps-react

import {Map, GoogleApiWrapper} from 'google-maps-react' var React = require('react') class GoogleMapContainer extends React.Component { render() { return( <Map google={this.props.google} sty ...

Encountering a JavaScript toJSON custom method causing a StackOverflow error

Unique Scenario Upon discovering this answer, a new idea struck me - creating an object from a JSON literal. This led me to believe I could do the opposite using the handy JSON method: JSON.stringify(myObject). Curious, I proceeded as follows: function ...

d3: It appears that my routes are replicating themselves, and I am unable to ascertain the cause

I've been diving deep into D3, studying the works of Mike Bostock and other experts in the field. I'm also going through Scott Murray's book on Interactive Data Visualization specifically focusing on D3. At the moment, my project involves c ...

Exploring the use of leaflets within LitElement

I have been working on a project involving LitElement components and I am looking to incorporate Leaflet into it. However, I am encountering difficulties with displaying the map properly. After installing Leaflet through npm in my project, I created a clas ...

Tips for retrieving arguments within a method called from a template in vue.js?

Here is an example where I am attempting to call a method from the template and pass in some arguments. How can I access those arguments from within the method? Snippet from script: methods: { showBinaries(job, id) { let test_url = process.en ...

Utilize the clearChart() function within Google charts in conjunction with vue-google-charts

I have integrated vue-google-charts to display various charts on my website. I want to allow users to compare different data sets, by enabling them to add or delete data from the chart. In order to achieve this functionality, I need to find a way to clear ...

What can be done to ensure that the a href tag is functioning as clickable?

Having an issue with my HTML and CSS code for a notification dropdown box. I am unable to click the tag, even after attempting to use JavaScript. Can't seem to figure out what's causing this problem. Any advice on how to make the tag clickable? ...