Updating Vue component property when Vuex store state changes: A step-by-step guide

As I work on developing a straightforward presentation tool using Vue js and Vuex to manage the app state, I am facing a challenge in implementing a feature that tracks changes in the presentation such as title modifications or slide additions/removals. Currently, my Vuex store structure is:

const state = {
    presentations: handover.presentations, //an array of objects retrieved from the DB
    currentPresentation: handover.presentations[0]
}

Within my Presentation component, the code looks like this:

export default {
    template: '#presentation',
    props: ['presentation'],
    data: () => {
        return {
            shadowPresentation: ''
        }
    },
    computed: {
        isSelected () {
            if (this.getSelectedPresentation !== null) {
                return this.presentation === this.getSelectedPresentation
            }
            return false
        },
        hasChanged () {
            if (this.shadowPresentation.title !== this.presentation.title) {
                return true
            }
            return false
        },
        ...mapGetters(['getSelectedPresentation'])
    },
    methods: mapActions({
        selectPresentation: 'selectPresentation'
    }),
    created () {
        const self = this
        self.shadowPresentation = {
            title: self.presentation.title,
            slides: []
        }

        self.presentation.slides.forEach(item => {
            self.shadowPresentation.slides.push(item)
        })
    }
}

Although I have managed to create a shadow copy of the presentation and detect changes effectively, I am struggling to update the shadow presentation when the actual presentation is saved. Since the savePresentation action is triggered in another component, I am unsure how to capture the 'save' event within the presentation component for updating the shadow presentation. If you have any insights on how I can achieve this functionality, your assistance would be greatly appreciated! Thank you in advance!

Answer №1

After exploring alternative solutions, I found a different approach to solve the problem I had initially asked about. Here is how I approached it:

Instead of having my vue store communicate an event to a component, as is typically done with vuex, I decided to revamp the structure of my presentation object. Originally, it looked like this:

{
    title: 'title',
    slides: []
}

I opted for a more intricate structure, which now looks like this:

{
    states: [{
        hash: md5(JSON.stringify(presentation)),
        content: presentation
    }],
    statesAhead: [],
    lastSaved: md5(JSON.stringify(presentation))
}

In the updated structure, the presentation object remains simple, but each presentation state now includes a hash generated from the stringified simple presentation object and the actual object itself. This allows me to generate a new state with a unique hash for every change in the presentation. By comparing the current state hash with the previously saved one tracked in the lastSaved property, I can easily implement undo/redo features by manipulating the states and statesAhead arrays. This solution surpassed my initial intentions and kept all my state management centralized within the vuex store without complicating or cluttering components.

I hope this explanation clarifies things for anyone who might find it useful. Cheers!

Answer №2

When I faced the challenge of updating properties in my user state, I came up with a solution that proved to be effective.

Updating User State in Vuex Store

updateUser (state, newProperties) {
    if (!state.user) {
        state.user = {}
    }
    for (var property in newProperties) {
        if (newProperties.hasOwnProperty(property)) {
            // Update the store state
            Vue.set(state.user, property, newProperties[property])
        }
    }
}

How to Use

Invoke the updateUser action from your Vue component

this.updateUser({status: 'active'})

Updated Object

{"user":{"emailVerified":true,"status":"active"},"version":"1.0.0"}

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

Tips for creating dynamic row styles in a fluid table layout?

Could someone help me figure this out? I'm not familiar with JavaScript and need assistance as I've never created it, only edited existing scripts. I have a layout with two tables side-by-side. On mobile devices, the second table is pushed below ...

Automated pagination integrated with automatic refreshing of div every few seconds

I am currently working on setting up a datatable and I need it to be displayed on the monitor in such a way that it can refresh the div and automatically paginate to the next page. However, whenever the div is refreshed, the auto-pagination gets cancelle ...

AngularJS Get request unable to fetch image URL due to receiving a "302 found" error

Trying to enhance my AngularJS app by incorporating an image from a random cat image site, using the URL received. Below is the snippet from my controller.js: 'use strict'; /* Controllers */ var catPath = "http://thecatapi.com/api/images/get? ...

Switch between various API content upon clicking (JavaScript)

Upon receiving data from an API in JSON format using PHP, I aim to incorporate a filter mechanism for displaying distinct content sourced from the API. For instance, by specifying a filter in my API call, I can retrieve separate datasets such as one with ...

Strategies for creating a dynamic progress bar using jQuery and JavaScript

I'm currently working on a project that involves increasing a percentage number while filling up the background color inside it based on the percentage value. The current setup is functional in terms of animating the background, but I need it to dynam ...

Sending a `refresh` to a Context

I'm struggling to pass a refetch function from a useQuery() hook into a context in order to call it within the context. I've been facing issues with type mismatches, and sometimes the app crashes with an error saying that refetch() is not a funct ...

Tips for safely storing JWT in the browser

I am currently working with Angular 10 on the front-end and obtaining a JWT from backend services. I am seeking the best method to securely store my Okta JWT in the browser while also mitigating the risk of XSS and XSRF attacks. I have looked into storing ...

Guide to incorporating Bootstrap and its dependencies into a Chrome extension powered by Vue using npm

As I delve into the world of webpack, vue, and vuex to create a chrome extension, I encountered an issue with loading Bootstrap 4 within the extension. Despite using the correct path for the node modules folder, I keep getting a file not found error when t ...

The React MUI Tab component triggers a re-render and clears the states of its child components

In our endeavor to create a Tab Page using React MUI, we aim for each Tab to contain a child component. While there are no issues when adding these child components individually to a page without tabs, problems arise when incorporating them within the Tab ...

There seems to be an issue with AppModule in your code. The error message states that it is not recognized as an NgModule and the problem

After upgrading to node 6, angular 4, typescript 2.3.2, and @angular/cli 1.02, I meticulously followed the steps outlined in the Guide for updating @angular/cli. I will include my entire package.json below in case there are any relevant details. The specif ...

Why does modifying a variable within the fetch URL result in undefined

I currently have a server running on the URL http://localhost:3000/. Within my JavaScript code, I have defined a variable called productCode with the value 'example-code55'. let productCode = 'example-code55'; const fetchData = async ...

Is there a way to access the body html element within a template in vue.js?

I'm struggling to add styles to the body element of my HTML page. It seems like I can't access it directly from the template because there's another body element nested inside the main body. Even when I try to change the style using JavaScri ...

The success variable of the Ajax running continuously in a loop is not being refreshed

Within this code snippet, a for loop is utilized to iterate through an array called netnos[] and update the variable 'nets' for each item. Ajax is then invoked to call a PHP script that generates a listing, which is successfully outputted to the ...

Positioning an HTML table with the use of a for loop in JavaScript

Detail of the project: -Utilizing a javascript for loop, my program extracts data from an external javascript array titled "arrays.js" and organizes it into an HTML table. The goal is to align the appropriate data under the "Date Name Address Amount" colum ...

What is the reason for the malfunction of this JavaScript code designed for a simple canvas operation?

I'm having trouble with the code below. It's supposed to display a black box on the screen, but for some reason it's not working properly. The page is titled Chatroom so at least that part seems to be correct... <html> <head> &l ...

Difficulty with formatting decimal points in JavaScript

I seem to be having an issue with decimal places in my code. Currently, it's showing the result as 123 123 12 but I actually need it to be displayed as 12 312 312. Is there anyone who can assist me with formatting this correctly? Here is the section ...

What advantages does event delegation in JavaScript offer compared to using jQuery's event handling?

Vanilla JavaScript: parentNode.addEventListener("click", function(event) { if (event.target === childNode) { code here } }); versus jQuery: $(parentNode).on("click", childNode, function() {}); ...

Troubleshooting problems with anchor-targets in Skrollr

I am experimenting with having divs overlap each other as the page is scrolled using Skrollr. Initially, I was able to achieve the desired effect with two divs. However, when trying to incorporate a third div, only the first and last ones seem to work prop ...

Trouble rendering Bootstrap dropdown in Vue2 component

I am experiencing a peculiar issue with my Vue child component, which is responsible for displaying a bootstrap modal and includes several fields, including one that should show a dropdown selection. Strangely, the dropdown button fails to activate, result ...

Creating dynamic templates for table rows in AngularJS directives

Is it possible to dynamically load an AngularJS Directive templateUrl while working within a table? In my scenario, I have the following HTML structure where I am repeating a tr element with a fw-rule directive: <tbody> <tr ng-repeat="rule in ...