@mongez/react-atom
Version:
A simple state management tool for React Js.
72 lines (71 loc) • 2.23 kB
JavaScript
;var atom$1=require('@mongez/atom'),react=require('react');function reactActions(data) {
return {
...data.actions,
Provider(props) {
const atom = this;
atom.update(props.value);
return props.children;
},
useWatch(key, callback) {
const atom = this;
react.useEffect(() => {
const event = atom.watch(key, callback);
return () => event.unsubscribe();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [key, callback]);
return atom.get(key);
},
useState() {
const atom = this;
const [value, setValue] = react.useState(atom.currentValue);
react.useEffect(() => {
const event = atom.onChange(setValue);
return () => event.unsubscribe();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
return [value, atom.update.bind(atom)];
},
useValue() {
const atom = this;
return atom.useState()[0];
},
use(key) {
const atom = this;
const value = atom.get(key);
const [, setValue] = react.useState(value);
react.useEffect(() => {
const event = atom.watch(key, setValue);
return () => event.unsubscribe();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [key]);
return value;
},
clone() {
return atom({
...data,
default: this.currentValue,
});
},
};
}
/**
* Create a new atom
*/
function atom(data) {
return atom$1.createAtom({
...data,
actions: reactActions(data),
});
}
/**
* Create a react collection atom to work with arrays
*/
function atomCollection(options) {
return atom$1.atomCollection({
...options,
actions: {
...options.actions,
...reactActions(options),
},
});
}exports.atom=atom;exports.atomCollection=atomCollection;//# sourceMappingURL=react-atom.js.map