Business logic in Vue 3 + Pinia

Viewed 134

Let's say I have a simple webshop application using Vue 3. Whenever the user adds an item to the cart, I store it locally in Pinia and I send this event information to the backend as well.

By default what I would do is I would add a action to the Pinia store like addItemToCart() which would update the local cartItems reactive variable and would also send the request to the backend like POST http://localhost/api/update-cart.

My idea is to introduce a service layer into my application. I would create a service like:

const useCartService = () => {
  const cartStore = useCartStore()

  const updateCartApi = useUpdateCartApi()

  const addItemToCart = async (item) => {
    cartStore.loading = true

    await updateCartApi.mutate(item)

    cartStore.items.push(item)

    cartStore.loading = false
  }

  return {
    loading: cartStore.loading,
    
    addItemToCart,
  }
}

Would it make sense to separate the business logic from the Pinia store like this? Is it considered as a anti-pattern, or is this approach commonly used in Vue?

0 Answers
Related