Problem with Pinia: nested array in an object

My unique store located within a vue3 application, contains an object called currentReservation with a property named pricings which is an array.

Each pricing includes an id and quantity. When I add a new pricing, it is added to both the store and component. The same goes for increasing or decreasing the quantity.

However, when I remove a pricing from the store using decreaseReservationPricing and the quantity reaches 0, the store gets updated but the storePricings property in my component does not remove the pricing. The quantity is adjusted but the object remains.

It's worth noting that even if I have initially added two pricings and then remove one, the component still displays two (although everything is working correctly in the store).

This is my component script:

<script setup lang="ts">
import { computed } from 'vue'
import { Pricing, ReservationPricing } from '@/@types/base'

import formsUiBlock from '@/components/forms/ui/Block.vue'
import CardsPricingItem from '@/components/cards/PricingItem.vue'

import { useReservationStore } from '@/stores/modules/reservation'

defineOptions({
  name: 'FormsBooking',
})

defineProps<{ pricings: Pricing[] }>()

const reservationStore = useReservationStore()
const storePricings = computed(() => reservationStore.currentReservation.pricings as ReservationPricing[]).value

function getPricingQuantity(id: string) {
  return storePricings.find(storePricing => storePricing.id === id)?.quantity || 0
}

// Manage pricing reservation quantity
function increaseReservationPricing(id: string) {
  const currentPricing = storePricings.find(pricing => pricing.id === id)

  if (!currentPricing) return storePricings.push({ id, quantity: 1 })
  currentPricing.quantity += 1
}

function decreaseReservationPricing(id: string) {
  const currentPricing = storePricings.find(pricing => pricing.id === id)

  if (currentPricing && currentPricing.quantity > 0) currentPricing.quantity -= 1
  if (currentPricing?.quantity === 0) reservationStore.cleanPricings()
}
</script>

Here is my store:

import { defineStore } from 'pinia'

// import { postReservation } from '@/api/reservation'
import { ReservationStore } from '../@types/base'
import { ReservationPricing } from '@/@types/base'

const currentReservationInit = {
  clientId: '',
  locationId: '',
  offerId: '',
  day: null,
  hours: {
    opening_hours: null,
    closing_hours: null,
  },
  firstName: '',
  lastName: '',
  email: '',
  phoneNumber: '',
  information: '',
  pricings: [],
  amount: null,
}

export const useReservationStore = defineStore('reservation', {
  state: (): ReservationStore => ({ currentReservation: currentReservationInit }),
  actions: {
    async postReservation() {
      // need to be set
    },
    cleanPricings() {
      const pricings = this.currentReservation.pricings as ReservationPricing[]
      this.currentReservation.pricings = pricings.filter(pricing => pricing.quantity !== 0)
    },
  },
})

Answer №1

One common error is immediately accessing the value, which hinders the reactivity of storePricings to changes in currentReservation.pricings, contradicting the purpose of a computed property.

The correct approach is:

const storePricings = computed(() => 
  reservationStore.currentReservation.pricings as ReservationPricing[]
)

To use it, do the following:

unref(storePricings).find(...)

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

Automatically scroll the chat box to the bottom

I came across a solution on Stackoverflow, but unfortunately, I am having trouble getting it to work properly. ... <div class="panel-body"> <ul id="mtchat" class="chat"> </ul> </div> ... The issue lies in the JavaScript t ...

What are the issues with using AJAX in conjunction with a for-loop?

I'm currently developing a small application that needs to create work schedules and calculate hours: . I've written the function kalkulacja() to calculate the inputs for each row and output the results through ajax. However, I'm facing an i ...

Preserve your Vuex state data without relying on vuex-persist

Here's a puzzling scenario that has me scratching my head... I am fetching user data from an API call and storing it in Vuex along with a Token. The initial setup works perfectly fine, as I can retrieve the user object using a getter when the compone ...

Using AngularJS to create a select dropdown menu with nested objects as the options

Currently, I am working on developing an AngularJS application with a complex data structure. The data source consists of an array of individuals with their languages and skill levels. My goal is to be able to filter these individuals based on language sk ...

React JS simple validator package not functioning properly with post-property date

I am currently utilizing the simple react validator package for form validation in my react JS project. For those interested, you can find the package at this link: https://www.npmjs.com/package/simple-react-validator However, I have encountered an issue w ...

Troubleshooting Karate - jbang.execute() (Node npm)

Need help with a question that's part of our project presentation. We are working on controlling the output of KARATE, ensuring it returns an OK or a KO depending on the test result. Currently, it always gives back 0 regardless of success or failure. ...

Issues with routing in NodeJS Express causing routes to not be called

I've been working on setting up a basic REST API using nodeJS. However, I am facing an issue where none of the endpoints are being called when I try to access them. Can someone guide me on what changes I need to make in order to get it working properl ...

unselect the button using jQuery

I want to trigger a popover when a variable exceeds a certain value, triggered by clicking a button: $(function () { $('[data-toggle="tooltip"]').tooltip({ trigger: 'manual', placement: 'top', titl ...

What exactly does Container-Based Authorization entail?

Did you know that the "XMLHttpRequest" object includes a method called "open," which has the option to supply a username and password? These parameters can be used for requests that require container-based authentication. Here is the method signature: op ...

What steps should I take to ensure my mineflayer sprints while trailing behind me?

I am developing a Mineflayer bot that follows me and tries to attack me. However, when I move far away from the bot, it stops following me. In addition, the bot has another issue where it falls while bridging due to its lack of intelligence. How can I im ...

Unpacking nested objects using dynamically generated property names in a React state - a guide

Having trouble with using setState and figuring out how to destructure the object with a dynamic property name, denoted by id. The state looks like this after computation: { "inputConfig": { "5d4d684cadf8750f7077c739": { "0": "5d4d ...

When you click on the input field, a file manager window will open. You can then select a file and the URL of the selected file will be automatically added to the

I need assistance with customizing the code to open the flmngr window and add the URL of the selected file to the input field when onclick. window.onFlmngrAndImgPenLoaded = function() { var elBtn = document.getElementById("btn"); // Style bu ...

The code "transform: rotate(' ')" does not seem to be functioning properly in Javascript

I set out to create a simple spin wheel exercise, but it quickly became more challenging than I anticipated. After researching how to make one online, I found code similar to mine that worked on a JSFiddle Example, yet my own code still didn't work. ...

Difficulties accessing MongoDb database using Node.js

Having issues when trying to read this data collection using mongoose and Node.js: I have a single JSON object within my Collection and I'm attempting to access it with the following code: materias.find().exec(function(err1,materias){ if(err ...

Issue: Trouble with ajax form functionality

I'm a beginner in ajax, js, and php. Recently, I set up a simple contact form. <form id="contact-form" method="post" action="process.php" role="form"> <div class="messages"></div> <div class="form-group"> <l ...

Having trouble integrating VueX store and router into Mocha tests

Latest Update To view the issue on VueX git repository that has been created, please follow this link: https://github.com/vuejs/vuex/issues/1509 If you want to replicate the problem, here is the link to the repository: https://github.com/djam90/vuex-vue- ...

What is the best method for setting up message scheduling for a Microsoft Teams bot based on different time

I am trying to figure out how to send messages to users from my bot at specific time intervals. Currently, I'm using agenda for scheduling messages, but I've run into an issue with the timezone discrepancy - agenda is 5:30 hours behind my timezon ...

JavaScript -Error: Unable to access the 'children' property as it is undefined

I'm currently working on creating a tree and calculating its height. The map array is properly initialized within the for loop, but when I run console.log(map+" this is map");, it displays [object Object],[object Object],[object Object],[object Objec ...

Create a list that starts with a header determined by an object's attribute within an array

Currently in Vue, I am attempting to create a list based on a specific property within an object. The array being retrieved from the vuex store is structured as follows: const array = [ { name: "British title string" nationality: "British" }, { ...

Caution: Exercise caution when rendering components in React due to unstable_flushDiscreteUpdates

Trying to utilize map to render a component, but encountering a warning: Warning: unstable_flushDiscreteUpdates: Cannot flush updates when React is already rendering. MyBooks.js import React, { useState, useEffect } from 'react'; import Action ...