Pinia sync with indexdb
I want to sync my Pinia store with IndexedDB.
Should I do this with $subscribe or $action?
I’ve heard that because of async/sync there can be problems.
Does anyone have an example of how to do it correctly?
2 Replies
Hi @🇨🇭 Marko Bolliger <cannap>. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
----------------------
Syncing a Pinia store with IndexedDB in a Nuxt app is possible, but there are important considerations regarding async/sync issues.
Should you use
$subscribe or $action?
- $subscribe: This method is commonly used to react to state changes in the store. However, since IndexedDB operations are asynchronous, using $subscribe can be tricky. If you perform async operations inside a $subscribe callback, you must handle potential race conditions and ensure you don't block the UI or introduce unexpected behavior.
- $action: Using actions to explicitly read/write to IndexedDB is more predictable, as you control when the async operations happen. However, this requires you to always use actions for state changes, which may not cover all direct mutations.
Example Approach
The knowledge sources do not provide a full, official example of syncing Pinia with IndexedDB, but they do show how to use IndexedDB with the unstorage library:
You can use this storage instance inside your Pinia actions to persist or load state.
Async/Sync Issues
Because IndexedDB is asynchronous, you should avoid direct mutations in $subscribe that expect synchronous persistence. Instead, use actions to handle both state changes and persistence, or debounce your persistence logic in $subscribe to avoid rapid, repeated writes.
Summary
- Prefer using actions for explicit, async-safe persistence.
- If using $subscribe, debounce or batch your IndexedDB writes to avoid async issues.
- There is no official, out-of-the-box Pinia + IndexedDB sync solution in the knowledge sources, but you can use the unstorage IndexedDB driver in your store logic for persistence tasks.
For more details on using IndexedDB with unstorage, see the unstorage browser driver docs. The Nuxt docs also mention using Pinia for state management, but do not provide a direct IndexedDB sync example Docs: State Management.
----------------------
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
----------------------<@87630674508394496> Kapa.ai is still learning and improving, please let me know how I did by reacting below.