How to write a predicate
This guide shows you how to let a condition read data that only your application holds, such as a cart total or an account level.
1. Define the predicate
Pass a predicates object to createClient():
import { createClient } from 'picked'
const client = createClient({
projectId: 'your-project-id',
predicates: {
'is-example-page': ({ location }) => location?.pathname === '/example',
'get-account-tier': async () => {
const data = await fetch('/api/get-account-tier').then((r) => r.json())
return data.result
},
},
})A predicate returns a boolean, a string, an array of strings, or undefined. It can also
return a promise that resolves to one of those.
2. Invoke it from a condition
condition: {
'==': [
{ invoke: { var: 'predicates.is-example-page' } },
true,
],
}Keep it pure and fast
- The same snapshot must always give the same result.
- Check that a response or a field is there before you read its value. Return
undefinedwhen the data is not available, and do not throw. - The SDK can invoke a predicate many times, so keep the logic small.
- Do not change the snapshot. It is frozen, and a change to it throws in strict mode.
Related
- Predicates — the state snapshot shape.
- About conditions and the logic engine — why predicates exist.
