@mongez/react-atom
Version:
A simple state management tool for React Js.
72 lines (71 loc) • 2.21 kB
JavaScript
import {createAtom,atomCollection as atomCollection$1}from'@mongez/atom';import {useEffect,useState}from'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;
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] = useState(atom.currentValue);
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] = useState(value);
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 createAtom({
...data,
actions: reactActions(data),
});
}
/**
* Create a react collection atom to work with arrays
*/
function atomCollection(options) {
return atomCollection$1({
...options,
actions: {
...options.actions,
...reactActions(options),
},
});
}export{atom,atomCollection};//# sourceMappingURL=react-atom.js.map