18

Does anyone know if it's possible to subscribe to a specific action in Pinia? I know there's a way to subscribe to all actions like this:

const subscribe = someStore.$onAction(callback, false)

But that means I have to compare action name to the one I want within the callback, like this:

websocketStore.$onAction(
  ({name}) => {
    if (name === 'specificAction') {
      console.log('do something')
    }
  }
)

So I wonder if there's a way to it better? (I'm using Pinia with Nuxt3)

Marek Miś
  • 259
  • 2
  • 8

2 Answers2

1

There is no official documentation to do it but we can create a plugin to perform same operation.

pinia.use(({ store }) => {
  let oldAction = store.$onAction;
  store.$onAction = function(action, cb){
      olddAction((ctx) => {
          if (ctx.name === action) cb.call(store);
      }
  }
})

Not tried it because never required, you can change plugin definition according to you.

santoshe61
  • 805
  • 8
  • 17
-1

Subscribing to actions

It is possible to observe actions and their outcome with store.$onAction(). The callback passed to it is executed before the action itself. after handling promises and allows you to execute a function after the action resolves. In a similar way, onError allows you to execute a function if the action throws or rejects.

export default {
  setup() {
    const someStore = useSomeStore()

    // this subscription will be kept even after the component is unmounted
    someStore.$onAction(callback, true)

    // ...
  },
}

Pinia official documentation

Vasil Gerginski
  • 559
  • 1
  • 6
  • 15
  • He specifically states that he knows about `store.$onAction`, but that it is not "clean". He wants to know if there is a way to subscribe to a _specific_ action. – Darryl Noakes Nov 11 '22 at 19:47