Is there a way to use Store within Data component with proper typing? #3907
-
Hi, I am using Alpine with typescript support. I have encountered a situation where I would like to use a store to manage, for instance, notifications globally on the app. I would then like whichever components to have access to this. However, the issue is that I cannot find any nice way to get Typescript support when using my store within a component without casting each time I want to access some property or method of the object in the store. I'll use a simplified example of a 'notifications' store, with a list of strings representing notifications, and a method to add a new notification. E.g:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
You can make a magic for it. That's what we did in production for toasts. Alpine.store('notifications', {
notifications: [],
add(thing) {
this.notifications.push(thing)
}
})
Alpine.magic('notify', () => (message) => Alpine.store('notifications').add(message)) For example. then you can do <button @click="$notify('Oh no')"> and this.$notify('Oh yeah!') |
Beta Was this translation helpful? Give feedback.
You can make a magic for it. That's what we did in production for toasts.
For example.
then you can do
and