Skip to content

Async Actions

Running asynchronous actions is as simple as making an async method on your store class.

store.ts
import { TwoAndEight } from '2n8'
import { fetchData } from './data-fetcher'
class Store extends TwoAndEight {
data: { id: string; name: string }[] = []
async loadDataButtonClicked() {
this.data = await fetchData()
}
}

As state is only emitted at the end of actions, you may find you’d like to emit earlier to trigger state changes in your app. For this you can use the special $emit action.

store.ts
import { TwoAndEight } from '2n8'
import { fetchData } from './data-fetcher'
class Store extends TwoAndEight {
data: { id: string; name: string }[] = []
status: 'idle' | 'pending' = 'idle'
async loadDataButtonClicked() {
this.status = 'pending'
this.$emit()
this.data = await fetchData()
this.status = 'idle'
}
}