Creating Pinia stores as classes

I am looking to streamline my code by creating a "Class" that can easily generate multiple identical Pinia stores with specific data for each. How can I achieve this efficiently?

import { ref } from 'vue'
import { defineStore } from 'pinia'

class StoreGenerator {
    constructor(store_name) {
        export const TeamStore = defineStore(store_name, () => {
            const objects = ref([])

            function add_object(info) {
                objects.value.push(info)
            }

            return { objects, add_object }
        })
    }
}

Answer №1

One issue is the syntax problem - you can use the export keyword at the top level.

Having a class might not be necessary as there isn't enough justification for having an instance of it. A factory function could work instead:

export const createMyStore = name => defineStore(name, () => { ... });

This can then be implemented in the store module like this:

export const myFooStore = createMyStore('foo');

While Pinia stores are great for modular usage, sometimes it might make sense to merge them into one store that manages multiple types of data:

export const myStore = defineStore('myStore', () => {
    const objects = ref({ foo: [], ... )

    function add_object(type, info) {
        objects.value[type].push(info)
    }

    return { objects, add_object }
})

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

Locate a specific item in an array using AngularJs based on a key and present its value on the View

Imagine you have an array of objects: $scope.objArr = [{key:1,value:'value1'},{key:2,value:'value2'},{key:3,value:'value3'}]; And a variable that corresponds to key. For instance: $scope.a = 3; In the Controller, you want ...

What's the scoop with for loops and grabbing elements?

In my code, I have a for loop that looks like this: for(i=0; i<6; i++) { if(i = 0) {a1 = '<div>something1</div>';} if(i >= 1 & i <= 5) {b1 = '<div>something2</div>';} } document.getElementById(&apos ...

JavaScript code that retrieves an array containing only the deleted images from the information obtained from the edit product page

Currently, I am working on an edit product page in react with a node backend. The situation is as follows: Initially, the product had 4 images (a.png, b.png, c.png, d.png). I have made updates by removing the a.png image and adding a new image e.png. So ...

The Value Entered in Angular is Unsaved

I have encountered an issue with my app's table functionality. The user can enter information into an input field and save it, but upon refreshing the page, the field appears empty as if no data was entered. Can someone please review my code snippet b ...

The dimensions of my grid object are constantly being altered by my interactive button

Recently, I started delving into vuejs and vuetify to work on a project management app for school. I encountered a simple problem where adding a button distorted the project bar. I tried nesting the button component within the project bar to rectify this i ...

The margin of the parent container is influencing the margin of the child element

Purple Working on displaying a rectangle shape in a browser using divs in my React project. Everything works fine, but when I add margin to the parent base and then draw the boxes, there's some space between the mouse cursor and the actual box. The ...

Prevent Sending Blank Forms with Stripe js

Currently, I am working on a solution to prevent users from submitting the stripe form when certain inputs are left empty. To achieve this, I have integrated stripe.js elements into my form and implemented the form submission handling within my vue compone ...

Steps for setting up a Node.js Express application that serves a Vue.js single page application

Currently, I am in the process of setting up a Node.js project that incorporates Express to create backend APIs and deliver a Single Page Application (SPA) designed with Vue.js. Upon initializing a project using the Vue cli, components such as the main fi ...

Error encountered during React application compilation due to SCSS loading issue

I've encountered an error while trying to develop a React application with Webpack. The issue seems to be related to the main SCSS file: ERROR in ./resources/scss/style.scss (./node_modules/css-loader/dist/cjs.js??ref--6-2!./node_modules/sass-loader/ ...

Blank page shown when routing with Angular in Rails

Hey there, I'm currently attempting to integrate Angular into my Rails application and unfortunately I'm encountering a problem where the HTML page shows up blank. Here's the code I have so far: app/views/index.html.erb <body> ...

Component library for Vue-cli 3 with built-in support for server-side rendering

I am in the process of developing a custom component library that I intend to distribute across various domains. Domains: Each domain is equipped with its own instance of Nuxt Every domain has included my-component-lib in their package.json Additional ...

JavaScript issue causing input fields to malfunction and clear text boxes

I apologize for the simplicity of this question, but I am struggling with an issue and seeking help. Here's the problem: my calculate() method is not clearing text input as expected when testing my page. Below is the HTML markup and script: <!DOC ...

Issues encountered while trying to open and close a div using jQuery

.box-one { border: 0.1em solid #ccc; } .dropdown-info { display: none; } <div class="box-one"> <div class="header"> <h3 class="text-center">Sample Header</h3> </div> <div class="dropdown-info"> <p ...

Clicking on a link initiates the dropdown menu for selecting an option

This project is specifically designed for mobile use, so there's no need to worry about how it will appear on desktop screens. In this project, I have an "a href" with an icon next to it that simulates a button. When a user clicks on it, a dropdown me ...

Unable to update a single object within an array using the spread operator

I am currently working on updating an object within an array and have encountered some issues. In my initial code, I successfully updated a specific property of the object inside the array like this: var equipment = this.equipments.find((e) => e.id === ...

Display the menu and submenus by making a request with $.get()

My menu with submenu is generated in JSON format, but I am facing issues displaying it on an HTML page using the provided code. Can someone please assist me in identifying what mistakes I might be making? let HandleClass = function() { ...

Issue with Cloud Code function preventing data from being saved

After successfully testing this code in Angular and getting the correct responses in console.log, I decided to migrate it to cloud code. Since the function manipulates data in the user table, I had to use the master key and implement it in cloud code. Howe ...

The issue with Angular's state.go function is that it is not properly refreshing the page, resulting in

Creating a mobile exam app that features multiple choice questions with previous and next question buttons. The transition between questions is handled using $state.go to load the same HTML page but with new questions and answer choices. // Within a servi ...

Issue with the useSWR hook causing the DOM not to update correctly due to mutation

My next.js app is utilizing the `useSWR` hook to fetch and populate data. const { data, error } = useSWR('/api/digest', fetcher, { revalidateOnFocus: false, }) The problem I am facing is that the DOM is not updating as expected after the `mu ...

Error encountered while using Google Translate with XMLHttpRequest (Missing 'Access-Control-Allow-Origin' header)

Trying to access a page that utilizes Google Translate is resulting in the following error: XMLHttpRequest cannot load http://translate.google.com/translate_a/element.js?cb=googleTranslateElementInit. No 'Access-Control-Allow-Origin' heade ...