pinia-plugin-persistedstate
pinia-plugin-persistedstate copied to clipboard
[core] only hydrate values present in `paths`
Clear and concise description of the problem
I'm unsure if it's an intended feature of this plugin or an overlooked "bug", but recently I encountered an issue where I was persisting an entire store to localStorage by accident in a Production app. To remedy this I added the paths
option to only persist the values I required, however users who already had the entire store in their localStorage (including stale values) are finding the Pinia store being fully hydrated by whats in localStorage rather than just the values present in paths
.
Suggested solution
function hydrateStore(
store: Store,
- { storage, serializer, key, debug }: Persistence,
+ { storage, serializer, key, paths, debug }: Persistence,
) {
try {
const fromStorage = storage?.getItem(key)
- if (fromStorage)
- store.$patch(serializer?.deserialize(fromStorage))
+ if (fromStorage){
+ const deserialisedStorage = serializer?.deserialize(fromStorage);
+ const hydratedObject = Array.isArray(paths) ? pick(deserialisedStorage, paths) : deserialisedStorage;
+ store.$patch(hydratedObject)
+ }
}
catch (e) {
if (debug)
console.error('[pinia-plugin-persistedstate]', e)
}
}
If you agree with the above solution I'm more than happy to put a PR in for it. Alternatively if this is an intended feature of the plugin then we could add another option to the Persistence
interface to toggle my new feature on/off as I think other people may also find this useful.
Alternative
No response
Additional context
No response
Validations
- [X] Follow our Code of Conduct
- [X] Read the Contributing Guide.
- [X] Check that there isn't already an issue that request the same feature to avoid creating a duplicate.