Skip to content

add option to pass a function to store.$patch() #403

Open
@unstoppablecarl

Description

@unstoppablecarl

Clear and concise description of the problem

There is no way to intercept and override the store.$patch() process.

Sometimes the order and grouping that state data is loaded into a pinia store matters a lot for computed properties and reactivity. Currently there is no way to control this as data is just sent to store.$patch(data). It is possible to re-order the keys of an object via the serializer option but, this does not allow control of data patch grouping.

There is currently no way to pick/omit object data within an array when hydrating.

There is also no way to control the order that different pinia stores are patched. I have not run into a problem that required this yet but, I suspect it could easily have the same ordering problem. I am not proposing a solution to this case but wanted to mention it for discussion.

Suggested solution

see: https://pinia.vuejs.org/core-concepts/state.html#Mutating-the-state

Example of new plugin option hydrate.

import {defineStore, StateTree, Store} from 'pinia'

defineStore('store', {
  state: () => ({
    first: '',
    second: '',
  }),
  persist: {
      hydrate: (deserialized: StateTree) => (store: Store) => {
        store.$patch({
          first: deserialized.first
        })

        store.$patch({
          second: deserialized.second
        })

      }
    },
  }
})

Changes made in core.ts

//
const deserialized = serializer.deserialize(fromStorage)
      const picked = pick
        ? deepPickUnsafe(deserialized, pick)

        : deserialized
      const omitted = omit
        ? deepOmitUnsafe(picked, omit)
        : picked
      // changes below
      if (hydrate) {
        store.$patch(hydrate(omitted))
      } else {
        store.$patch(omitted)
      }
//

Alternative

No response

Additional context

No response

Validations

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions