Creating one
import { atom, proxy } from 'atemno';
const celsius = atom('celsius', 20);
const fahrenheit = proxy<number>('fahrenheit', {
get: $ => ($.get(celsius) * 9) / 5 + 32,
set($, value) {
$.set(celsius, ((value - 32) * 5) / 9);
},
});
domain.get(fahrenheit); // 68
domain.set(fahrenheit, 212);
domain.get(celsius); // 100get is a computation, with the same tracker context, the same laziness and the same cache. set receives an action context and the written value, and decides what to write where. The proxy stores nothing of its own.
Anywhere an atom goes
A proxy atom is a writable source, so domain.set, $.set inside actions and computations, and the React hooks for atoms all accept it.
const [value, setValue] = useAtomState(fahrenheit);Unlike an atom, a write does not compare the value first. set always runs, and the atoms it writes do their own equality checks.
One write, several steps
When set writes several atoms, they are written in one batch, the same as in an action. Observers of the proxy are called once, with the value after every write.
const fullName = proxy<string>('fullName', {
get: $ => `${$.get(first)} ${$.get(last)}`,
set($, value) {
const [nextFirst = '', nextLast = ''] = value.split(' ');
$.set(first, nextFirst);
$.set(last, nextLast);
},
});
domain.observe(fullName, console.log);
domain.set(fullName, 'Grace Hopper');
// "Grace Hopper"Names and lifetime
Proxy atoms have their own namespace in a domain, so a proxy and a computed with the same name do not share a node. Like a computed, a proxy is released once nothing tracks it, and the atoms it read are released with it if nothing else holds them.