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)
},
},
})