jotai
Version:
👻 Primitive and flexible state management for React
32 lines (31 loc) • 774 B
JavaScript
let keyCount = 0; // global key count for all atoms
export function atom(read, write) {
const key = `atom${++keyCount}`;
const config = {
toString() {
return process.env.NODE_ENV !== 'production' && this.debugLabel
? key + ':' + this.debugLabel
: key;
},
};
if (typeof read === 'function') {
config.read = read;
}
else {
config.init = read;
config.read = defaultRead;
config.write = defaultWrite;
}
if (write) {
config.write = write;
}
return config;
}
function defaultRead(get) {
return get(this);
}
function defaultWrite(get, set, arg) {
return set(this, typeof arg === 'function'
? arg(get(this))
: arg);
}