Updating the single element in an object with Vuex - any tips?

After going through various stack overflow questions and guidance, I have reached this point. Essentially, my code is supposed to return a new array by updating a single id. However, even though the updatedProducts array is being generated correctly when I console.log it, my store state is not being updated. Here is how my state object looks:

allProducts:[
            {
                "product_name": '',
                "code": '',
                "id": ''

            }
        ],

Below is the mutation I am using:

UPDATE_PRODUCT : ({allProducts},payload) =>{
            let updatedProducts = allProducts.map(product => {
                if(product.id === payload.id){
                    return Object.assign({}, product, payload);
                }
                return product;
            })
            allProducts = updatedProducts;
        }

Although I can see the correct result when logging updatedProducts, the allProducts array remains unchanged. Any ideas why?

Answer №1

Make sure to include the state as the first parameter in your mutation method:

state:{
    allProducts:[
        {
            "product_name": '',
            "code": '',
            "id": ''

        }
    ]  
}

Here is the correct mutation implementation:

 UPDATE_PRODUCT : (state,payload) =>{
        let updatedProducts = state.allProducts.map(product => {
            if(product.id === payload.id){
                return Object.assign({}, product, payload);
            }
            return product;
        })
        state.allProducts = updatedProducts.slice();
    }

Answer №2

When you replace the reference, you lose the original one

allItems = newItems;

Instead of replacing it, you should mutate it like this

allItems.length = 0;
Array.prototype.push.apply(allItems, newItems);

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

Having a <cfinput> tag nested inside a JavaScript block is leading to errors

I'm currently working with jQuery to append a new row to a table, but I've encountered an issue when trying to insert a <cfinput> field. Strangely, ColdFusion seems to be interpreting the <cfinput> tag within the JavaScript block and ...

The error message "Type 'Observable<void>' cannot be assigned to type 'Observable<IComment[]>' in ngrx" is indicating a mismatch in types within ngrx

Recently, I've been diving into learning ngrx by following a guide. The code in the guide matches mine, but I encountered the following error: Type 'Observable<void>' is not assignable to type 'Observable<IComment[]>'. ...

Ensure there is no blank space between the bootstrap labels when using ng-repeat

When using ng-repeat in Angular.js to add labels, they appear without spacing. Check out this Plunker for a demonstration. However, if I add labels manually by copying the HTML code, they are displayed with whitespace. Is there a way to add white space b ...

Can you explain the purpose of this function on Google PlusOne?

Within the code snippet below: (function() { var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true; po.src = 'https://apis.google.com/js/plusone.js'; var s = document.getElementsByT ...

Is there a way to show "Closed" or "Open" depending on the time in Vue.js HTML?

Here is the JSON data representing the hours of operation for a particular shop: { "status": true, "data": { "pid": 1, "bussinessName": "ard", "services": "looking for passionate", "inventory": [], "workHr": ...

When transitioning from component to page, the HTTP request fails to execute

I have created a dashboard with a component called userInfo on the homepage. This component maps through all users and displays their information. Each user has a display button next to them, which leads to the userDisplay page where the selected user&apos ...

Guide to Including an Object in AngularJS Scope

I am completely new to Angular JS and mongod. My goal is to add a new ingredient field to this page for the specific drink that the + button is clicked on. Here is how my view looks like: UI Image This is what my .jade file contains: block content ...

How to implement div scrolling on button click using Angular 4

Is there a way to make the contents of a div scroll to the left when one button is clicked and to the right when another button is clicked? I've tried using ScrollLeft, but it doesn't seem to be working... Here's the HTML code: <button ...

What does the error "Cannot access property 'length' of null when using 'angular'" mean?

I am currently working on counting the initial li items and encountering an issue with 'Cannot read property 'length' of null' after fetching data from the server using a unit test case. Here is my code: import { ComponentFixture, Tes ...

Incrementing a variable based on a condition in JavaScript

Currently, I am working on a project where I have a variable called "total" that needs to be assigned a number (or price) and then incremented when certain options are selected or checked. Below is the code that I have developed up to this point. This sni ...

Find the closest multiple of 3 for the given number

In our coding project, we have encountered a scenario where the input must be divisible by 3. For instance, if someone enters the number 9, everything works perfectly as expected. However, when a user inputs the number 7, the program returns the result wit ...

What is the best way to cut off multiple lines of text and display the remaining strings at the

Currently, I am working on a project that involves implementing a gallery feature. The challenge lies in displaying file names which can be quite lengthy, and we are restricted to showing only 2 lines of text. While this can be achieved using line clamp an ...

Creating variables with increasing names can be done by using a loop in the

I'm having trouble figuring out how to approach this issue. Currently, I have a variable set up to store an object: var myobject = new object(); Everything is working fine; the name of the variable is 'my object' and it contains a new obj ...

Manage and display data in Vue.js using the CLI

I'm currently developing a form where users can input data and I need to display that data on another page using Vue.js Below is the form I have created: <form id="main-contact-form" class="contact-form r ...

Encountering the "Cannot set headers after they are sent to the client" error within an Express.js application

In my recent project, I created a middleware to authenticate users and verify if they are verified or not. Initially, when I access protected routes for the first time, everything works fine and I receive success messages along with verification of the JWT ...

Using a conditional statement to wrap a react Route

Currently, I am facing a challenge while working with react router. Initially, I had two distinct components being rendered under the same route - one with a parameter and one without (this was how the routes were distinguished). Now, my goal is to add opt ...

What is the process for displaying user input on the console?

How can I ensure that the server is receiving user input? What steps should I take to print this input to the console? Currently, the console.log statement only displays "About to create new room", but I require the user input as well. Client-Side: // C ...

Simple steps to change the appearance of the delete button from an ajax button to an html button

I need help transitioning the delete button from an ajax button to an html button in my code. Currently, the delete button functions using ajax/javascript and when clicked, a modal window pops up asking for confirmation before deleting the vote. However, ...

The node.js application was unable to locate the '../HMS/server/models/user' file

Hi there! I'm currently working on an application with a folder structure as shown below. I want to use the following line in my passport.js file: var User = require('../server/models/user'); However, I encountered the error below after tr ...

Getting latitude and longitude from Google Maps in a React Native appHere are the steps to

Looking to retrieve the latitude and longitude from Google using React Native. As a newcomer to React Native, I have been unable to find any resources to address this issue. Any assistance would be greatly appreciated. Thanks! Thanks ...