Using the Vuex getter to populate a component with data using the v-for directive

I am currently constructing a vue2 component, utilizing a vuex store object. The structure of the component is as follows:

<template>
    <ul id="display">
        <li v-for="item in sourceData()">
            {{item.id}}
        </li>
    </ul>
</template>

<script>  
    export default {
        mounted: function () {
            console.log('mounted')
        },
        computed: {
            sourceData: function() {
                return this.$store.getters.visibleSource
            }
        }
    }
</script>

The store gets populated through an ajax call at the beginning of the process, within the main javascript entry:

new Vue({
    store,
    el: '#app',
    mounted: function() {
        this.$http.get('/map/' + this.source_key + '/' + this.destination_key)
            .then(function (response) {
                store.commit('populate', response.data)
            })
            .catch(function (error) {
                console.dir(error);
            });
    }
});

Although there are no evident errors and the Vue devtools explorer shows that my component's sourceData attribute contains numerous items, nothing seems to be rendered on the page. Even with good data in the component, the template does not display anything.

Is it necessary to implement some sort of callback to trigger the component after the vuex store has been populated?

EDIT: Here is the code for the store:

import Vue from 'vue';
import Vuex from 'vuex';
import { getSource, getDestination } from './getters'

Vue.use(Vuex)

export const store = new Vuex.Store({
    state: {
        field_source: [],
        field_destination: []
    },
    getters: {
        visibleSource: state => {
            // Formats the data 
            return getSource(state.field_source)
        },
        visibleDestination: state => {
            return getDestination(state.field_destination)
        }
    },
    mutations: {
        populate(state, data) {
            state.field_source = data.source
            state.field_destination = data.destination
        }
    }
})

EDIT2: It might not be due to the v-for loop - I do not see any elements being rendered from the template, not even the main ul tag, which should at least appear empty if there were any issues further down the script.

Answer №1

sourceData is not a method, but a computed property. Avoid invoking it unnecessarily. Instead of v-for="item in sourceData()", use v-for="item in sourceData".

In your 'populate' mutation, you are replacing the observed/reactive objects.

To handle this, either utilize Vue.set():

mutations: {
    populate(state, data) {
        // previously state.field_source = data.source
        Vue.set(state, 'field_source', data.source);
        // previously state.field_destination = data.destination
        Vue.set(state, 'field_destination', data.destination);
    }
}

Or add all elements to the existing observed/reactive arrays:

mutations: {
    populate(state, data) {
        // previously state.field_source = data.source
        state.field_source.push(...data.source);
        // previously state.field_destination = data.destination
        state.field_destination.push(...data.destination);
    }
}

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

Exploring the realm of styling with React JS

Currently, I am facing an issue while working with material-ui for my web design. Here is the code snippet that I am using: const useStyles = makeStyles((theme) => ({ card: { marginTop: theme.spacing(10), direction:"column", alig ...

Discovering the magic of obtaining a random element in Vue.js

I have 3 captivating hero images along with their unique content, and I am looking to showcase them randomly to users each time they refresh the page! My challenge lies in efficiently loading these large hero images using jQuery. Currently, all three imag ...

Changing the sliding underline effect in a jQuery navigation bar

Recently, I implemented a sliding underline element in my navigation bar. The idea is that when a link is hovered over, the underline smoothly transitions to that element. You can take a look at the codepen example here: https://codepen.io/lucasengnz/pen/e ...

What is the best way to remove current markers on google maps?

This is how I implemented it in my project. The issue I'm facing is that the clearAirports function does not seem to clear any existing markers on the map or show any errors in the Google console. googleMaps: { map: null, init: function () { ...

What steps should I take to fix the error "Unused left side of comma operator with no side effects.ts(2695)" in my React project?

import React from "react"; import { useRecoilState } from "recoil"; import { Industry, industryState } from "../atoms/industriesAtoms"; const manageIndustryData = () => { const [industryStateValue, setIndustryStateValue] ...

"Upon initial loading, the Vue3 Nested RouterLink does not appear to be active

Currently, I have a primary <RouterView/> responsible for the main site navigation. However, one of the routes also has child components. In this scenario, I have created another named router view called <RouterView name="helper"/>. H ...

Searching for a specific row of data by ID in a massive CSV file using Node.js

Can someone recommend an npm package that is ideal for iterating over a csv file, locating a specific value, and updating/appending to that particular row? I don't have any code to display at the moment as I'm in the process of testing different ...

Error in Typescript: Function expects two different types as parameters, but one of the types does not have the specified property

There's a function in my code that accepts two types as parameters. handleDragging(e: CustomEvent<SelectionHandleDragEventType | GridHandleDragEventType>) { e.stopPropagation(); const newValue = this.computeValuesFromPosition(e.detail.x ...

How can we organize and display the data from two linked arrays, one containing player names and the other containing

Looking for help on how to rank 3 players based on their scores using arrays. I've hit a roadblock and need guidance! Here's a brief example: Player 1 : Taylor Score Taylor : 15 Player 2 : Jordan Score Jordan : 20 Player 3 : Alex Score Alex : ...

After installing Ember and running the Ember server, I noticed that the node_modules directory appears to be empty. This issue is occurring on my Windows 10 x64 PC

Welcome to the command console: C:\Users\Documents\emberjs>ember server node_modules seem to be empty, consider running `npm install` Ember-cli version: 2.14.2 Node version: 6.11.2 Operating System: Windows 32-bit x64 I'm a beg ...

Techniques within the identical module, constantly refreshing

In the realm of HTML, I am well-versed in accomplishing this task. However, I am reluctant to conceal it using a div tag and class. Here is my current setup: <template> <div id="navJade" class="inactive"> <h1>Jade Skill Calculations ...

What could be the reason behind my Vue 3 page not refreshing its content when navigating to a new page?

I am experiencing an issue with my Vue3 template file that is fetching data from Strapi. While it works fine on my local machine, the content only loads correctly on the first page load when I run it online. Subsequent page changes do not update the cont ...

Pass the PHP data back to my existing webpage for JavaScript to retrieve

I recently set up a form on my WordPress website for users to submit data. Once the form is submitted, I use AJAX to create a new post without having to reload the page. I now need to figure out how to pass the post ID, a simple integer, back to the page s ...

Merging angular-file-upload with multer

I am facing a challenge in integrating the angular file upload plugin with multer to create a fully Single Page Application (SPA). I am currently stuck on uploading multiple files through multer. Below is how my multer options are set up in my node route. ...

Executing a serverless function in Next.js using getStaticPaths: A step-by-step guide

In my current project, I am utilizing Next.js and the Vercel deployment workflow. To set up page generation at build time, I have been following a guide that demonstrates how to generate pages based on an external API's response. // At build time, t ...

Why is Angular.orderBy not displaying any data on the Page?

Embarking on my first Angular project with Firebase Firestore, I am excited to showcase some of the code below. I recently learned Angular and here is what I have accomplished so far: Component.html <section class="rank"> <p class=& ...

Error: Unable to access attributes of null object (specifically 'accessToken')

After following a YouTube tutorial by Lama for creating an E-commerce application, I attempted to add a logout feature on the admin page that was not covered in the tutorial. To implement this, I used Redux to grab the currentUser and set it to null to suc ...

Serialization of JSON is not possible for the data type <code>[object Promise]</code>

Full error: Error: Issue when serializing data .b retrieved from getStaticProps in "/". Cause: object ("[object Promise]") cannot be serialized as JSON. Please ensure only JSON serializable data types are returned. Encountering an er ...

Bidirectional binding with complex objects

In my Angular2 app, I have a class called MyClass with the following structure: export class MyClass { name: Object; } The name object is used to load the current language dynamically. Currently, for two-way binding, I am initializing it like this: it ...

Trigger the opening of a class or window upon pressing the button

Good evening, I'm attempting to create a functionality where pressing a specific button will open a window. However, I am unsure of how to achieve this using CSS classes. My initial thought was to add a new class in the CSS file and call it every ti ...