Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to subscribe to a specific action in Pinia

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)

like image 441
Marek Miś Avatar asked Nov 24 '25 17:11

Marek Miś


1 Answers

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.

like image 97
santoshe61 Avatar answered Nov 27 '25 02:11

santoshe61



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!