Updating a property within an object in Vue using Pinia

I am currently utilizing the pinia library and I am seeking guidance on how to update a property within an object. Within my state.cart, I have an array of objects representing various products, all of which contain a property named quantity. As this quantity can be modified, I need to effectively "update" the cart data.

This is the approach I attempted:

state: () => ({
   cart: []
}),

actions: {
  updateQuantityOfProduct(product, val) {
    const prod = this.cart.find((item) => item.id === product.id)
    prod.quantity = val
    this.$patch({
      cart: this.cart,
    })
  },
}

However, it appears that this method does not yield the desired results. The cart remains unchanged, even after refreshing the page, indicating that the quantity of the product has reverted to its pre-change value.

What steps should I take to resolve this issue? Additionally, where might I be going wrong in my implementation?

Answer №1

It seems like we both faced a similar problem initially. However, after facing the same issue and revising my answer multiple times, I was able to resolve it successfully. I'm not certain why your solution isn't working, but perhaps you could try the alternative version provided below:

const useCartState = defineStore('carts', {
  state: () => {
    return {
      cartItems: [],
    }
  },
  actions: {
    updateProductQuantity(product, value) {
      this.cartItems.map(item => {
        if (item.id === product.id) {
          item.quantity = value;
        }
      })
    },
  },
})

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 is the optimal location for storing JSON data while dynamically loading via AJAX?

Let's imagine a scenario where there is an HTML page hosting a dynamic modal box. Clicking on different links within the page triggers the modal to open, each showing different content based on the clicked link. The dialog contents are fetched using A ...

Replicating the existing div content into a textarea

I wanted to create a tool for my workplace as a learning project in html, CSS and JS. It's a timer that tracks how long I spend on tasks. Currently, I have the timer resetting itself but I'm facing an issue where the paused time is not being log ...

Navigating through promises within a nested loop

I have an array of objects that looks like this: After aggregating some results, I end up with a result having the same structure as shown below: results = [ {id: 1, test: biology, candidates:[ {cid: 11},{cid: 12},{cid: 13}]}, {id: 2, test: chemistr ...

Arranging data in an HTML table by dynamically populating it with information retrieved from a server

UPDATE 4/16/2012: All issues have been resolved, and the sorting functions are now functioning correctly. Timezones have been converted to their corresponding one-letter UTC codes (A-Z). The only remaining task is implementing Daylight Savings Time checks ...

Unable to locate update. A complete reload is necessary in webpack

Below is the content of my webpack.config.js file. Despite adding ['react-hot' ,'babel'], I am unable to resolve the issue. var webpack = require('webpack'); var path = require('path'); var APP_DIR = path.resolve(__ ...

Using VueJS to conditionally apply a class within a template

My current setup involves a template that generates cards for individual projects pulled from Firebase and stored in an array. <template> <div class="projects-wrapper"> <div class="individual-project" v-bind:key="proje ...

What is preventing me from utilizing middleware in my express route?

I have a project in progress where I am developing an API. As part of this process, I need to implement a user system and ensure secure access to the API. Below is the middleware function used for validation: 'use strict' const jwt = require(& ...

Transfer a concealed input value to javascript using the href attribute

I have a question about using javascript to handle the href attribute. Here is the code snippet I am working with: <script> window.onunload = refreshParent; function refreshParent() { var SAPno = document.getElementById('Hidden ...

In order to streamline our production environment, I must deactivate Vue.js devtools, while ensuring they remain active during development mode

Is there a way to prevent users from inspecting the app using devtools in production mode while keeping it enabled for local/development mode? I've tried setting up .env and .env.production files with the VUE_APP_ROOT_API variable but it doesn't ...

Revamping the website to become a Progressive Web App

I am in the process of transforming my website into a Progressive Web App (PWA) and have made some updates to my code to facilitate this: index.html <script> if('serviceWorker' in navigator) { navigator.serviceWorker.registe ...

Matching wildcard paths using Express

Seeking help with routing in Express. I am trying to have both /m/objectID and /m/someslug/ObjectID directed to the same function. My current setup is as follows: app.get("/m/:id", ...); app.get("/m/(.*)/:id", ...); The first route is working properly, b ...

Unable to invoke the Socket.on() function in NodeJS

I have set up a PHP web app and I am trying to integrate nodeJS into it. I followed a tutorial on nodeJS and got it working fine on localhost:3000. But now, I want to run it on a specific URL like localhost/final/chat/chat_index.html. To achieve this, here ...

Show the React component once the typewriter effect animation is complete

Hello there, I am looking to showcase my social links once the Typewriter effect finishes typing out a sentence in TypeScript. As someone new to React, I'm not quite sure how to make it happen though. Take a look at the code snippet below: ` import ...

Unable to write to file due to permission restrictions from EPERM. Will delete existing file and create a new one. This action

I am encountering an issue with my file system function that involves deleting a file and creating a new one with updated data. The error occurs randomly, not consistently, happening approximately every other time the code runs. Below is my current impleme ...

Guide to redirecting data from an external POST request to a customer through a GET request

Within my Express application, I am currently dealing with both incoming POST requests containing a payload from an external source and GET requests sent by my client: router.post('/liveReleaseStore', (req, res) => { let data = req.body.m ...

Encountering Firebase error auth/admin-restricted-operation following createUserWithEmailAndPassword operation

Encountering a Firebase error (auth/admin-restricted-operation) when attempting to sign up with email, despite enabling user creation with email in project settings. Could the issue lie within my project settings? I have been scouring the internet for hour ...

What steps should I follow to ensure that 'npm test' locates my karma.conf.js file successfully?

My application has the following structure: Web (Asp net core) | |--wwwroot |--ClientApp | |--app | | |-- ... (typescript modules, *.spec.js files etc.) | | | |--karma.config.js | |--test-main.js | |--Controllers |--config.json files for web etc. W ...

What is the best way to position the list element to align with the top of a div container?

To see a live example, visit this link. My goal is to create a line that separates two li elements within a nested ul. However, the line ends up taking the width of the container ul instead of the div containing the entire structure. In the provided examp ...

Having trouble uploading data to the database using a combination of Vue.js and Laravel backend framework

I've been facing an issue where my attempt to submit a record to my SQL database from a Vue component using Laravel API is not yielding any results. Despite comparing my code with other functioning examples, I have yet to find a solution. Below is th ...

Tips for retrieving the value of a dynamic and multi-update id using jQuery and Ajax

I'm in need of assistance with a few different tasks: Firstly, I am looking to understand how to retrieve the id of an input element when it is dynamically generated from a database. In the HTML, it displays something like field 1 -> id = "pa ...