Singles
Singles are perhaps the most versatile Module type that Providence provides. Singles allow you to represent an arbitrary data structure in your state manager without creating extra boilerplate for their maintenance.
Singles are commonly composed into Lists.
Single Controllers
As with all Providence modules, you will want to interact with Singles through their controllers.
To get a new single controller:
import {useSingle} from '@opencraft/providence-redux/hooks'
// Declare a type in TypeScript to get typechecking for your single's data structure.
declare interface MyStructureType {
id: number,
name: string,
}
const MyComponent = () => {
controller = useSingle<MyStructureType>('currentItem', {endpoint: 'https://example.com/api/endpoint/'})
// ... The rest of your component code goes here!
}
import {useSingle} from '@opencraft/providence-redux/hooks'
const MyComponent = () => {
controller = useSingle('currentItem', {endpoint: 'https://example.com/api/endpoint/'})
// ... The rest of your component code goes here!
}
// Coming once the Pinia module is completed.
// Coming once the Pinia module is completed.
Single Module Options
In most cases, you'll only need to hand the retrieval function the endpoint of the object you're retrieving, but you may also need to set a number of other attributes.
Check the Single Module Reference documentation.
Controller Reference
The single controller is the main interface by which you interact with the single module-- and thus your state management library. Check here for a primer on controllers as a concept.
Check the full Single Controller Reference Documentation here.
Patchers
Patchers are a special, controller-like wrapper around the attributes of singles. They act as proxies for sending patch requests to a server. This is especially useful for cases like Vue's v-model
, but also allows for more terse functions in the case of React's event listeners.
Say you had a controller for a Product type:
declare interface Product {
id: number,
name: string,
description: string,
hidden: boolean,
}
You could update the value of hidden
by setting its value on the autogenerated patcher:
// Output: false
console.log(controller.x.hidden)
controller.p.hidden.model = true
// Output: true
console.log(controller.p.hidden.model)
// Still false, as this value is canonical until the server update is completed:
console.log(controller.x.hidden)
// Also true, since the update is not complete:
console.log(controller.p.hidden.dirty)
The value on a Patcher's model field is instantly updated, and in the background, a patch
request is dispatched to the Single's endpoint with the data {"hidden": true}
.
Up until the patcher succeeds, its dirty flag stays true. If an error occurs while performing the patch request, errors will appear in controller.p.hidden.errors
. See below for more attributes and methods.