Vuex fails to trigger updates on Vue computed properties

I have been integrating vuex as a middleware between firestore and my vue application. The structure of my vuex store is as follows:

const store = new Vuex.Store({
    state: {
        posts: [],
    },

    mutations: {
        add_post(state, post) {
            state.posts[post.id] = post;
        },
    },

    actions: {
        async load_post(context, id) {
            let post = await db
                .collection('posts')
                .where('post_id', '==', id)
                .get();
            post = post.docs[0]; 

            post = {id, ...post.data()};
            context.commit('add_post', post);
        },
    }
});

Within my Vue component:

export default {
    name: 'Post',
    beforeMount() {
        const id = this.$route.params.id;
        this.$store.dispatch('load_post', id);
    },
    data() {
        return {
            id: this.$route.params.id
        };
    },
    computed: {
        content() {
            return this.$store.state.posts[this.id];
        }
    }
};

When browsing the site, everything runs smoothly. However, if I refresh the page, the content property becomes undefined. After investigating, I believe it's trying to access the store while it's still loading (hence being undefined), and then failing to update when the store is ready. I've experimented with watchers and vuex's mapState but haven't found a solution yet... any ideas?

Answer №1

Vue might not recognize a modification in a nested attribute that isn't initially defined in the state when loaded. To address this issue, consider updating your mutation function as follows:


update_post(state, post) {
   Vue.set(state.posts, post.id, post);
}

// Ensure to include 'import Vue from 'vue';' at the beginning of your store file whenever using the Vue.set() method
import Vue from 'vue';

Answer №2

If you are facing a Vue reactivity issue, the solution lies in updating state.posts in vuex to ensure that the component remains reactive. Simply mutating state.posts[post.id] will not suffice as it does not update the reference of state.posts.

mutations: {
  add_post(state, post) {
      state.posts = {
        ...state.posts,
        [post.id]: post
      }
  },
},

Alternatively, you can utilize JSON.parse(JSON.stringify()) method.

add_post(state, post) {
  state.posts[post.id] = post;
  state.posts = JSON.parse(JSON.stringify(state.posts))
},

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

The WebDriver encountered an error while trying to click on an element

When using Selenium WebDriver, I am facing an issue with selecting an item from a drop-down list. The element I want to click on is labeled as "game club". Despite attempting to select different elements, I keep encountering an error stating that none of ...

Utilizing properties and functions within the onBlur() method of React-Native Formik

I'm currently attempting to trigger a function and the formikProps in my onBlur TextInput function simultaneously. <TextInput onBlur={() => { formikProps.handleBlur('password') setFocused(false) } /> My Goal: Wh ...

The intended 'this' keyword is unfortunately replaced by an incorrect '

Whenever the this keywords are used inside the onScroll function, they seem to represent the wrong context. Inside the function, it refers to the window, which is understandable. I was attempting to use the => arrow notation to maintain the correct refe ...

Switch the hue when altered

My document contains various input elements such as text, radio buttons, and checkboxes. I want each of these elements to change color when a change is made. This is the method I am currently using: $("document").on('click', 'change', ...

What is the best way to transfer a value to v-model using emit?

I'm having trouble passing the selected value from a select field to v-model. Currently, the code only seems to work with a v-text-field. <script> export default { name: 'FormSelect', props: { model ...

Server-based WebRTC video streaming

Is it possible to stream a video from the client side and have other viewers join via a server? How can I achieve this setup? ...

Excessive recursion in MooTools causing issues with Google Maps integration

Hello, I'm currently facing an issue with my WordPress plugin. Whenever Mootools is included, Google Maps are not displaying due to "too much recursion" error. Here is a snippet of the code for reference: Any suggestions or workarounds for this incon ...

Contrast between a pair of methods for submitting a request in an Express application

I am curious about the contrast in making requests using two different approaches within an Express application. Firstly, I encountered this code snippet in a repository: http.get(options, res => { res.on('data', data => { r ...

Splicing using only one parameter will make changes to the array without deleting the entire array

let myArray = ['a','b','c','d','e']; console.log(myArray.splice(1)); console.log(myArray); Looking at the splice documentation, it mentions that not providing a delete parameter would remove all array item ...

Fill Datalist with Database Information

As a beginner in javascript and php, I am trying to populate a datalist from a mysql table. However, I am facing some difficulties with the relevant codes provided below. Although I can fetch data from the database, I am struggling to display them in the d ...

inject the HTML content into the <div> container

Snippet: https://jsfiddle.net/x9ghz1ko/ (Includes notes.) In my HTML file, there are two distinct sections: <section class="desktop_only"> and <section class="mobile_only">. The challenge lies in positioning a JavaScript sc ...

The ins and outs of import and export output explained

I'm currently struggling to understand the output of Import/Export Statement. For example, if I were to write this code: import React, { Component } from 'react'; import Cperson from '../components/person/person.js'; console.log ...

Navigating with React in ES5

My email addresses are "[email protected]" and "[email protected]". I am facing an issue with the following minimal example code: var React = require('react'); var ReactDOM = require('react-dom'); var Router = require(' ...

Issue: The system is unable to locate the module titled '@kyleshockey/object-assign-deep'

Recently, I installed the accept-language npm module. When attempting to start my project afterwards, an error message appeared: Error: Cannot find module '@kyleshockey/object-assign-deep' What steps can I take to fix this problem? ...

Transmitting personalized information with Cylon.js and SocketIO

After making adjustments to my code based on the example provided here https://github.com/hybridgroup/cylon-api-socketio/tree/master/examples/robot_events_commands This is the complete server code, currently running on an Edison board. Everything functio ...

Tips for preventing a component from being cached in Nuxt.js

I'm currently experimenting with using the Vue.js keep-alive prop within Nuxt.js. My goal is to cache all components except for one - the basket component, which I want to exclude from caching. I want this component to be refreshed every time a user a ...

Utilizing Vue.js with XML data streams

I ran into a problem while working on my personal site with Vue.js. My goal is to display the five latest posts from my Jekyll blog on the page. To achieve this, I am checking the feed at http://todayilearned.dk/feed.xml. However, I'm struggling to ...

What could be causing issues with my setup for submitting forms in Django and using jQuery AJAX?

Although I have encountered questions like this numerous times before, I am struggling to make my AJAX form function correctly using jQuery on the client side and Django on the server side. Despite researching extensively, I have not come across a step-by- ...

Leveraging setters in JavaScript for modifying properties

The MDN documentation for the set function appears to suggest that a setter defined in [ECMAScript 2015] should not exist in an object literal alongside a data entry for the same property. [ECMAScript 2015] setter must not appear in an object literal .. ...

Using react-formik to implement responsive fields in a React application

I've been tasked with creating a dynamic form that pulls fields from a STRAPI api. The form will serve as a component to be reused on different pages, each displaying the same form but with varying fields based on the data returned by Strapi. Here i ...