Combining two states in the Vuex store

In my Vuex store, I have two states:

  • notes (synced notes with the server/DB)
  • localNotes (unsynced notes that will move to 'notes' state upon syncing)

To display the notes in a list, I use a getter that merges the two objects and returns the merged result.

The issue I am facing is that when I add a new note to one of the states, it doesn't show up in the list because the getter doesn't detect the change. I believe this is due to returning a variable instead of a function.

Here is the code for my getter:

const getters = {
    notesObject: (state, getters, rootState, rootGetters) => {
        let result = {};
        let mergedObject = {...state.notes, ...state.localNotes};
        Object.keys(mergedObject).forEach(key => {
            const item = mergedObject[key];
            if (rootGetters['tags/activeKey'] === null) {
                result[key] = item
            } else if (item.tag_id === rootGetters['tags/activeKey']) {
                result[key] = item
            }
        });
        return result;
    },
};

Example object structure:

example: {
            5: {
                title: 'Testing title',
                text: 'text'
            },
            6: {
                title: 'Testing title',
                text: 'text'
            }
        }

I need help finding the best solution for this issue. One idea was to use a watcher, but I know it's best to avoid them.

One possible solution is to have the watcher merge the two states into a new state so that the getter no longer needs to perform the merge operation.

Answer №1

Vue's reactivity system may not automatically detect when new properties are added. To ensure proper detection, consider using the Vue.set(object, key, value) method for adding new properties.

When updating your mutation function, switch from

state.localObject[payload.id] = payload;
to
Vue.set(state.localObject, payload.id, payload);
. This adjustment should enable the getter to function correctly.

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

What are the benefits of removing event listeners in Reactjs?

In my opinion, the event listeners need to be reliable and consistent. React.useEffect(() => { const height = window.addEventListener("resize", () => { setWindowSize(window.innerHeight); }); return () => window.remov ...

Leveraging Angular to retrieve images from Google Feed API

I'm currently working on developing an RSS reader and trying to integrate images from the Google Feed API. While I have successfully extracted the publishedDate and contentSnippet, I am facing difficulty in getting the image src. The code snippets bel ...

[Vuetify alert]: The server-side rendered virtual DOM structure does not align with the client-side content (Nuxt, Vue, and lerna monorepo)

I am currently facing an issue while attempting to run a basic Nuxt application within a lerna monorepo, which includes an external Vue component constructed using vue-cli. Initially, the page displays the content of the component (rendered by the server) ...

What are the steps to implement background synchronization in place of making fetch requests upon UI changes?

Consider this scenario: A straightforward web application with a comments feature. In my view, when a user submits a comment, the following steps would typically unfold: Show UI loader; Update the front-end state; Send a fetch request to the API to post ...

Error in Material UI when using the select component

CustomComponent.js:98 UI Error: The value undefined provided for the selection is out of range. Please make sure to select a value that matches one of the available options or ''. The available options are: `All`, `Software Development`, `Qualit ...

Ways to swap out element within ViewContainerRef in Angular

I am currently expanding my knowledge of Angular and I have encountered a challenge regarding dynamically creating components and swapping them within a single container. Here is the setup: <ng-container #container></ng-container> Here are the ...

Sophisticated method in JavaScript to conceal and reveal div elements

My knowledge of front-end web development is strongest in HTML and CSS, but when it comes to JavaScript, I feel like there must be a more efficient way to achieve the functionality I want. On my website, I have a set of <li> items that, when clicked ...

What is the best way to implement momentJS globally in VueJS 2?

Currently working with Vue.js version 2.6.11 Trying to set up in main.js as follows: import moment from 'moment' moment.locale('nl'); Object.definePrototype(Vue.prototype, '$moment', { value: moment }); Encountering an error ...

Having trouble with accessing properties like `d3.svg()`, `d3.scale()` and other features of d3js within an Angular 2 environment

Struggling to incorporate d3.js into angular2. Below is the command I used to install d3 in Angular2: npm install --save d3 install --save-dev @types/d3 This is how my package.json appears: { "name": "my-app", "version": "0.0.0", "license": "M ...

Troubleshooting jQuery: Unable to refresh the webpage

I have a PHP page that contains a form, checkboxes, and a submit button. I added an if statement to execute a PHP script I created when the button is clicked, which deletes certain values from the selected rows. The button functions properly and changes s ...

How can I assign a distinct identifier to individual instances of Vue.js components?

I am looking to build a Vue.js component that includes a label and an input. Here is an example of the structure I have in mind: <label for="inputId">Label text</label> <input id="inputId" type="text" /> Is ...

What is the best method to customize CSS in ExtJS 5.0 by overriding a function?

Is there a way to dynamically add a rule to existing CSS using code, particularly in overrides? For example: var sheets = document.styleSheets; // Some code omitted for simplicity var sheet = sheets[sheets.length - 1]; sheet.insertRule('.overlay {flo ...

Each time the page is reloaded, the Ajax call is triggered, resulting in duplicated

When I visit my homepage, one of the components on the page looks like this: import React, {Component} from 'react'; class BlogPostsWidget extends Component { render() { $.ajax({ type: "GET", url: 'https://example.com/wp- ...

Tips for showcasing my database in real-time using Php, JavaScript, jQuery and AJAX

Is there a way to display my MySQL database in real-time through AJAX without overloading it with excessive queries? I am currently utilizing jQuery's load function, but I suspect there may be a more efficient method. Can you offer any advice or alter ...

Transform the header style columns of react-js Material-tables into rows

Currently experimenting with gradient designs on a material table. While I am able to apply the right color combination to the rows, I seem to be getting column-based results on the title of the table. Attached is a screenshot of my output for reference. ...

What is causing the reluctance of my Angular test to accept my custom form validation function?

I'm currently facing an issue with testing an angular component called "FooComponent" using Karma/Jasmine. Snippet of code from foo.component.spec.ts file: describe('FooComponent', () => { let component: FooComponent let fixture ...

Why won't Node.js let me redirect to my error page?

I've been putting together my newsletter project with the Mailchimp API, everything seems to be working fine except for when I try to redirect to a failure page if the status code is not 200. The browser shows an error message saying 'localhost r ...

Styling on Material UI Button disappears upon refreshing the page

I've been using the useStyles function to style my login page, and everything looks great except for one issue. After refreshing the page, all styles remain intact except for the button element, which loses its styling. Login.js: import { useEffect, ...

Transform an array of strings into a JSON object or array

Is there a way to transform a JavaScript string array into a JSON string? var arr = "{'id': '10', 'name': 'test1'},{'id': '11', 'name': 'test2'}"; This would allow for easy a ...

Can different classes be assigned as "dragenter" targets?

Is it possible to apply the Jquery "dragenter" event to multiple targets or classes simultaneously? I tried this approach, but it doesn't seem to be working: $('.list').on('dragenter','.class1, .class2', function(e) { ...