# State management
# Core Store
createStore()
is a custom store implementation based on reactive
/refs
on Vue. If you need access to data from multiple components it is advisable to use the SDK store instead of Vuex.
# Class based
createStore()
function supports class based stores. Getters will be automatically converted to a Vue computed.
Example:
// store/my-store.js
class MyStore {
id = 'myStoreId'
state = {
foo: 4,
}
get double() {
return this.state.foo * 2
}
}
export function useMyStore() {
return createStore(new MyStore())
}
WARNING
NOTE: The id
property is the only thing required. Everything else is optional. Internally the object
will be converted to a reactive Observable.
# Watchers
If a function starts with on_
it will be converted to a watcher.
Example:
import { createStore } from '@pitcher/core'
class MyStore {
id = 'myStoreId'
state = {
foo: 4,
bar: 5,
}
get double() {
return this.state.foo * 2
}
get sum() {
return this.state.foo + this.state.bar
}
// watcher
on_state_foo() {
console.log('foo changed')
}
}
export function useMyStore() {
return createStore(new MyStore())
}
# In Components
If you need local state in a component it is advisable to use the following to keep it simple
import { reactive } from '@vue/composition-api'
...
setup() {
const state = reactive({})
}
# Async Store
useAsyncStore
is a higher order composable to add async state management functionality to createStore
. It only needs to be used when the data that is stored in the store comes from an async data provider.
useAsyncStore
adds loading
, error
, success
statuses to the store. Also caches the data that's fetched from the function and uses the same data in every consecutive call.
useAsyncStore
accepts three arguments;
id
: store's unique id. This argument is used as the cache key for the storefetchFunction
: any async function that returns data, the data that's returned from this function gets stored in the store.- An options object containing:
disabled
: if the store has async dependencies usingdisabled
disables the store from firing the function until those requirements are met (e.g. if you want to cache a data with a given id and the id may or may not be present, this options disables the store until the id is provided)select
: this function is called with the raw data which comes from the fetched function, and if provided the data that is returned from this function is stored at the store. Useful for making some parsing/mutations beforehand to the data.defaultValue
: initialises the store with this value.refetchOnSyncFinish
: refreshes the data inside the store with each sync. Default is set totrue
.