I have several Pinia stores that are supposed to share a set of actions and getters, but I'm not quite sure how to implement this efficiently.
I'm building an application that allows users to manage many different media (books, movies, TV shows, etc.). The way I'm currently thinking about it is to have a store for each media type, such as BookStore, MovieStore, etc. Many getters and operations (such as count
and deleteOne
) are identical between these different stores.
How to implement DRY here? The examples in the Pinia documentation focus on reusing actions and getters within other stores, but I don't think this fully addresses my use case of directly inheriting a set of getters and setters.
Is the inheritance approach I'm trying here an anti-pattern?
If you want some functionality to be shared across not all stores, you can use composable.
You can create a separate composable function and pass part of the store instance into it.
I made an example for you on codesandbox.
Here is a short example of codesandbox:
common.ts
Then in any store you can use it like this:
fooStore.ts
This way you can compose any function, object, etc. in any storage or in any component.
This can be achieved using plugins docs
Sample movie:
You have multiple stores, each state using a shared naming scheme:
Each store will have the same CRUD operation, just the URL changes
Create plugin:
Provide plug-ins for Pinia:
Example movieStore.js (using shared actions and state)
Usage examples in components
Editor: 1
If you pass the context into the plugin, you can access the store and the options passed into it, from which you can check the store ID and only return the specific store as shown below
I created a very basic example using 3 stores, the above check is available in codesandbox here