Selectors
Selectors are functions that take in a leaf's value and returns another value.
const user = new Forest({
$value: {
username: '',
password: ''
},
selectors: {
canSubmit(leaf) {
const {username, password} = leaf.value;
return username && password && leaf.$.passwordIsValid();
},
passwordIsValid(leaf) {
const {password} = leaf.value;
return typeof password === 'string' && (/a-z/.test(password) && /A-Z/.test(password) && /\d/.test(password))
}
}
});
user.do.set_username('Bob');
user.do.set_password('password');
console.log('first try valid: ', user.$.canSubmit());
user.do.setPassword('AveryGoodPassword1123');
console.log('second try valid:', user.$.canSubmit());
/**
* first try valid: false
* second try valid: true
*/
Selectors can be async, if desired. They can also preform other utilities like calling AJAX endpoints, etc.
State is frozen during a selector.
Its not just a bad idea to change state in a selector - it is not allowed. The point of a selector is to return a derived value from, the state, as is, with no side effects.
Why use selectors?
Actions also can return values. However, actions are wrapped in a transactional context. as they can change state. Selectors are a utility mechanic, and they are faster than actions because they lack the insulation that Forest uses to protect and provide rollback values in the case of a failed action.
Last updated on April 8, 2023