The computed properties in my VueJS/X data template aren't loading in the correct order

Apologies for any language barriers, I am using a translator tool to communicate. As a beginner in VUE and VUE X, I know there may be some mistakes in my approach. Currently, I am facing an issue with displaying a publication based on its ID.

Below is the DATA provided:

    data(){
    return {
        list: [this.$store.dispatch('allPublications')],
        id:'',
        feed: '',
    }
},

Here is the STORE action implemented:

    publicationId:({commit}, messages) => {
  instance.get('/publications/' + messages.id)
  .then(function(response){
    commit('setMessage', response.data.publication)
    console.log(response)
    this.feed = response.data.publication.data
  })
  .catch(function(error){
    console.log(error)
  })
},

Highlighted below is the computed section of the code:

    computed: {
    ...mapState({
        user: 'profileUser',
        publication: 'publicationFeed',
        message: 'publicationInfos'
        }),

        message(){
            return this.$store.state.message;
        },
},

Next, here is the state setup:

    setMessage: function(state, message){
  state.message = message
},

Now, let's look at the template structure used for rendering:

<template>
           <div class="card-body" @click="publicationId(message.id)">
            <span class="badge bg-secondary">{{ message.User.username }}</span>
            <div class="dropdown-divider"></div>
            <div class="card-text d-flex justify-content-between align-items-md-center">
                <p class="card-text d-flex flex-start">{{ message.message }}</p>
            </div>
            <span class="message__date">{{ message.createdAt.split('T')[0]}}</span>
        </div>
        <img class="card-img-top" alt="..." :src="message.image">

In addition, here are some screenshots that could assist in understanding the situation better:

VUE google chrome tool

Before reloading the page, everything is OK

After reloading the page, everything is going wrong

While everything functions correctly without a page reload, encountering errors post-reload leads to disappearance of computed values and inability to retrieve data.

I have explored various resources but haven't found a solution yet; grateful for any guidance provided! Thank you!

Answer №1

After facing a challenging issue, I finally found a solution by following these steps:

    data() {
    return {
        componentLoaded: false,
        list: [this.$store.dispatch('allPublications')],
        id: '',
        feed: '',
    }
},

Upon mounting the component:

    mounted() {
    this.componentLoaded = true;
    this.id = this.$route.params.id;
    this.$store.dispatch('publicationId', { id: this.$route.params.id })
},

Utilizing computed properties:

    computed: {
    message() {
        if (!this.componentLoaded) {
            return null
        } else {
            return this.$store.state.message;
        }
    },
},

I also included a v-if statement in the template for validation purposes

<template>
<div class="verification" v-if="componentLoaded === true">
    <div class="card-body" @click="publicationId(message.id)">
        <span class="badge bg-secondary">{{ message.User.username }}</span>
        <div class="dropdown-divider"></div>
        <div class="card-text d-flex justify-content-between align-items-md-center">
            <p class="card-text d-flex flex-start">{{ message.message }}</p>
        </div>
        <span class="message__date">{{ message.createdAt.split('T')[0] }}</span>
    </div>
    <img class="card-img-top" alt="..." :src="message.image" />
</div>
<div v-else>
    <h1>test</h1>
</div>

This method worked effectively for me, and I hope it proves helpful to others facing similar challenges.

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

Angular's ng serve is experiencing issues with mark-compacts near the heap limit, leading to an unsuccessful allocation

Encountering an issue while running ng serve in my Angular project. However, ng build --prod seems to be working fine. <--- Last few GCs ---> [4916:00000276B1C57010] 588109 ms: Scavenge (reduce) 8180.7 (8204.3) -> 8180.6 (8205.1) MB, 3 ...

Redirecting to a separate component outside the current structure and transferring a callback function

How can I navigate from App.js, the default component, to a new component that is not within the hierarchy while passing a function? I have three components: Question for displaying questions, Upvote for upvoting, and Downvote for downvoting. Here is the ...

Prevent the continuous looping of tree generation using Breadth-First Search (

My current assignment involves writing a program to determine the shortest path between a knight and a target tile on a chessboard. The task requires me to represent the knight's possible moves in a tree structure and utilize recursion to find paths t ...

What distinguishes a WAV file recorded from a user's microphone versus a WAV file imported from a separate file? Identifying the unique characteristics that may be causing bugs

Currently, I have two methods available for sending a WAV file to the server. Users can either upload the file directly or record it using their microphone. After the files are sent, they undergo a similar processing workflow. The file is uploaded to S3 an ...

What methods can be used to determine if a bound function is equal when performing unit testing?

I am looking to verify that when I pass an argument to a function, it is indeed a function reference even though the function reference is passed using the bind() method. Take a look at this shortened code snippet that needs to be tested: initialize: fun ...

Order an array based on another array using the underscore library in Javascript

I'm trying to align the order of two arrays of objects. Here are the arrays: Array 1: var firstArray = [ {id: "1", value: 1}, {id: "5", value: 0.5}, {id: "3", value: 0.25}, {id: "4", value: 0.125}, {id: "2", value: 0.0625} ]; Array 2: var secondAr ...

Can someone break down the meaning of "returning $http.post" in Angular while developing a factory service?

I've been grappling with the concept of return $http.post('/some link') and can't seem to fully grasp it. Imagine I have a node/express backend and am utilizing Angular for my frontend. Within my api, there is a function like this: v ...

I encountered an issue with Material UI tabs showing the error message: "Failed prop type: The prop `children` is not supported. Please remove it."

Recently, I started using Material UI tabs in my project for the first time. Everything seems to be working fine except for one issue that keeps showing up in the console while running the project: Failed prop type: The prop `children` is not supported. Pl ...

Need to update React textarea with value that is currently set as readonly

In my React application, I have a textarea that is populated with a specific value. My goal is to allow this textarea to be updated and then submit the form in order to update the corresponding row in the database. <textarea id="description" className= ...

guaranteed function to retrieve React elements

Is there a solution for the issue where if-else doesn't work in run build but works in run dev? The only way I've found to make it work is by using a react hook, but I'm unsure which one to use and where to implement it. import { useAdd ...

Trouble deploying Firebase Cloud Functions

I am attempting to implement the following two functions: exports.increaseWaitinglistCounters = functions.database .ref('waitinglists/$iid/$uid') .onCreate(async () => { await admin .database() .ref(`waitinglistCounters/$ii ...

After subscribing, my Angular template fails to refresh

Currently, I am facing an issue with my Angular 17 project where the data fetched from the API is not updating the template. This means that despite receiving the data, I am unable to display it on the page. The code snippet below shows the service compon ...

Unable to display notifications within the modal using Notistack MUI in React JS

Hey there, I'm currently utilizing react in combination with MUI. To display notifications, I've integrated a library called notistack. My goal is to show an error message in a dialog if there's a failure in the API response. Here's the ...

Having trouble editing a record in Vue.js/Vuetify/Axios after it has been created

After creating a new record, I encounter an issue where updates don't reflect in the database until I refresh the page. This behavior has left me puzzled about its cause. The sequence of events goes as follows: 1) New record creation --> data sen ...

"Exploring the world of Angular, promises, and effective caching strategies in

In my Angular application, there is a service responsible for loading items from the server. When an item is selected in a view, the corresponding item should be retrieved from the list and displayed in detail. The issue arises when I reload the page – ...

Unresolved error causing promise to throw an exception

My code is causing an error when resolve is called: Possibly unhandled Error: undefined at Promise$_rejecter (c:\projects\Test\promiseftp\node_modules\bluebird\js\main\promise.js:602:58) at WriteStream.<a ...

AJAX messaging system utilizes setInterval to stack identifiers

Currently, I am working on a chat project at school that involves AJAX. The issue I am facing is when a user clicks on a link (representing the person they want to chat with), an onclick event triggers a function called load(id) where the id of the person ...

Unique Title: "Tailored Scrolling Method with Dynamic Flicker

I created a scroll animation function for transitioning to the next div. It works smoothly in Firefox, but I am experiencing flickering issues in Chrome when scrolling multiple times. Here is a fiddle Check out the code snippet below: var mousewheelevt ...

Setting values to an array based on the index of a specific name in JavaScript - a guide

How can I set values to an array if it has an index in the name field? Here is the sample data: [ { "column": "created_at[0]", "name": "created_at[0]", "type": "range", ...

The Debate: Single Javascript File vs. Lazy Loading

Imagine you're working on a massive javascript-powered web application with minimal page refreshes in mind, containing around 80-100MB of unminified javascript to give an idea of its scale. The theory is that by lazy-loading your javascript files, yo ...