Component not being updated by Vuex

I am currently working on a website using Vue and Vuex with TypeScript. (Apologies for the lengthy code samples)

Within my project, I have a Store Module called 'musicArtists':

const actions: ActionTree<MusicArtist[], any> = {
    getAllArtists({ commit }): any {
        Providers.musicArtists.getAll(
            (musicArtists: MusicArtist[]) => {
                console.log("MusicArtist!", musicArtists);
                commit("setArtists", musicArtists);
            },
            (error: Error) => {
                console.log("Error!", error);
            },
        );
    },
};

const mutations: MutationTree<MusicArtist[]> = {
    setArtists(state: MusicArtist[], artists: MusicArtist[]) {
        state = artists;
        console.log("setArtists", state, artists);
    },
};

export default{
    namespaced: true,
    getters: {

    },
    state: {
        artists : [],
    },
    mutations,
    actions,
};

In addition to the Store Module, I also have a Component:

<template>
    <div id="page-music-audio">
        <Artist v-for="artist in artists" v-bind:artist="artist"/>
        <h2>{{ count }}</h2>
    </div>
</template>

<script lang="ts">
import { Component, Vue } from "vue-property-decorator";
import { mapState } from "vuex";

import Artist from "@/components/music/Artist.vue";
import { MusicArtist } from "@/common/models/music-artist";
import { Providers } from "@/providers";
import store from "@/store/index";


@Component({
    created: () => {
        console.log("length", store.state.musicArtists.artists.length);
        if (!store.state.musicArtists.artists.length) {
            store.dispatch("musicArtists/getAllArtists", { root: true });
        }
    },
    components: {
        Artist,
    },
    computed: {
        ...mapState("musicArtists", ["artists"]),
        count: () => {
            return store.state.musicArtists.artists.length;
        },
    },
    data: () => {
        return {
            store,
        };
    },
})
export default class Audio extends Vue {}
</script>

<style lang="scss">

</style>

However, upon navigating to the sub page where this component is located, it appears that initially there are no 'artists' displayed, as the array is empty. Subsequently, the API calls are made to load the 'artists' into the state, confirmed by console output. Strangely, the page does not update with the new information, failing to display the artists or the count. (The Artist component simply shows the name of the artist).

I'm questioning whether I have overlooked something very simple and obvious (entirely possible) or if there is another underlying issue at play???

Answer №1

In order to improve the code, I am considering removing Vuex and transferring the logic into the class itself rather than relying on decorators to access 'this'. Despite attempting this approach with the store, I have yet to achieve success.

@Component({
    components: {
        Artist,
    },
})
export default class Audio extends Vue {
    artists: MusicArtist[];

    constructor() {
        super();
        this.artists = [];
    }

    created() {
        console.log("length", this.artists.length);
        if (!this.artists.length) {
            Providers.musicArtists.getAll(
                (musicArtists: MusicArtist[]) => {
                    console.log("MusicArtist!", musicArtists);
                    this.artists = musicArtists;
                },
                (error: Error) => {
                    console.log("Error!", error);
                },
            );
        }
    }
}

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

Building a single page web application using TypeScript and webpack - a step-by-step guide

For a while now, I've been working on single page applications using Angular. However, I'm interested in creating a single page application without utilizing the entire framework. My goal is to have just one .html file and one javascript file, w ...

Displaying the size of a JSON array in Vue.js

When working on my Vue.js project, I encountered an issue. I wanted to display the length of specific data from an API. However, when I used the code below, the status sold length appeared as 5 repeated five times instead of just once with a value of 5. ...

Vue will display only the most recent component that has been registered

In Vue, it always renders the last registered component and ignores any others, even if they are not used at all. //main.ts import Vue from 'vue'; Vue.component('component-one', require('./components/ComponentOne.vue')); ...

Unable to retrieve information from v-for as it returns null data

Currently facing an issue with retrieving data from the database using Axios in Vue.js. I am able to see the data in my database through Vue.js developer tools like this: https://i.stack.imgur.com/n7BRO.png However, when attempting to loop through the dat ...

Getting the URL of the page before in Vue Router - a quick guide

Is there a way to retrieve the previous page link or URL in vue-router? I am trying to achieve this. Any guidance on how to do it? const link = this.$router.getPrevLink(); // Is there such a function? this.$router.push(link); A similar concept is using t ...

Switching hamburger menu icons in Vue.js

I am trying to change a hamburger menu icon in my header to a cross icon when it is clicked. I have created a function in the computed property of my Vue template, but I'm not entirely sure about the implementation. How can I achieve this? Below is t ...

Determine in an efficient way during mouseover if the control key is being pressed with Vue

My initial approach to tracking whether the control key (ctrl) is pressed while hovering over a <section> is as follows: <template> <section v-on:mouseover="controlKeyPressed = $event.ctrl">...</section> </template> Howeve ...

Creating dynamic components in vue-router based on route parameters

Is it possible to dynamically use components in Vue based on the value of a route parameter? For instance, let's say we have the following scenario: path: '/model/:modelName', components: { default: ModelDefinition.models.find((model) =& ...

Bring in an Angular Component into a different Component by stating the name of the component as an input parameter

In my project, I am looking to develop an angle component made up of multiple sub-components. The end goal is to construct a versatile tree component with nodes that cater to different data types. Each data type in the tree component will import specific s ...

The Angular material slider experiences issues with functionality when paired with the *ngFor directive

Having a unique problem that I could easily replicate on stackblitz. When using multiple mat sliders generated from a *ngFor loop with numbers as values, encountering an issue where moving the first slider affects all others. Subsequent drags only update ...

Enhancing JEST testing efficiency using vue.js

I am currently working on a basic app with a few components and only one test for the Login.vue component. Whenever I run jest, it seems to take around 10 to 20 seconds each time. I was wondering if there are any ways to improve the performance or if this ...

What is the best way to seamlessly redirect a user from Django to a Vue app without the need for them to login a

Imagine I have a Django application using templates, and now I want to create a button that seamlessly redirects the user to an admin app built in Vue.js. What is the most efficient approach to redirecting the user to the Vue service without requiring th ...

Issue encountered in Angular 2 while attempting to import TypeScript classes using a single file

Upon loading my Angular 2 application, I encountered the following error: EXCEPTION: Error: Uncaught (in promise): Unexpected piped value 'undefined' on the View of component 'DashboardComponent' An interesting observation is that by ...

axios encountering a 400 bad request error during the get request

I've hit a roadblock for some time now while trying to make a call to my API to fetch data using the GET method. I keep getting a 400 bad request error in Postman, even though I am able to successfully retrieve the data with a status code of 200. I ha ...

JavaScript module declarations in TypeScript

Recently, I delved into the world of a Node library known as bpmn-js (npmjs.com). This library is coded in JavaScript and I wanted to incorporate typings, which led me to explore d.ts files. My folder structure looks like this webapp @types bpmn ...

What are the best scenarios for creating a constructor in Angular 2 using Typescript?

Check out these sample constructors I found in the Angular 2 documentation: export class AppComponent implements OnInit { title = 'Tour of heroes'; heroes: Hero[]; selectedHero: Hero; constructor(private heroService: HeroService ...

An issue with event listeners in Vue 3 and Pixi.js arises when working with DisplayObjects that are either created as properties of classes or inherited from parent classes

Utilizing PIXI js in conjunction with Vue 3 (see code snippet below) Due to the consistent pattern of most graphics with varying behaviors and properties, we opted for an OOP approach with TypeScript to prevent code duplication. However, following this app ...

guidelines for rendering a Vue component within a Vue file using vue-server-renderer

Starting the rendering component with vuejs is my goal. I currently have a basic node server set up. const Vue = require('vue'); const server = require('express')(); const template = require('fs').readFileSync('index. ...

Angular Tutorial: Understanding the Difference Between TypeScript's Colon and Equal To

I've been diving into the Angular4 tutorial examples to learn more about it. https://angular.io/docs/ts/latest/tutorial/toh-pt1.html One of the code snippets from the tutorial is as follows: import { Component } from '@angular/core'; @Co ...

Utilizing the same uuid twice along with Vuex and the unique identifier generation tool uuidv4

Within my vuex store, there is a function to create a post. This function generates a json Object containing a unique uuid using uuidv4(). However, I have noticed that if I execute the function multiple times, the uuid remains the same each time (unless I ...