@mongez/react-atom
Version:
A simple state management tool for React Js.
106 lines (105 loc) • 2.87 kB
JavaScript
;var reactAtom=require('./react-atom.js');/**
* Create a boolean atom
*/
function openAtom(key, defaultOpened = false) {
return reactAtom.atom({
key,
default: defaultOpened,
actions: {
toggle() {
this.update(!this.currentValue);
},
open() {
this.update(true);
},
close() {
this.update(false);
},
useOpened() {
return this.useState()[0];
},
},
});
}
/**
* Create a loading atom
*/
function loadingAtom(key, defaultLoading = false) {
const atomHandler = reactAtom.atom({
key,
default: defaultLoading,
actions: {
startLoading() {
this.update(true);
},
stopLoading() {
this.update(false);
},
toggleLoading() {
this.update(!this.currentValue);
},
},
});
return atomHandler;
}
/**
* Create a fetching atom
*/
function fetchingAtom(key, defaultValue = null, defaultFetching = true) {
return reactAtom.atom({
key,
actions: {
startLoading() {
this.change("isLoading", true);
},
stopLoading() {
this.change("isLoading", false);
},
useLoading() {
return this.use("isLoading");
},
useData() {
return this.use("data");
},
useError() {
return this.use("error");
},
usePagination() {
return this.use("pagination");
},
success(data, pagination) {
this.merge({
isLoading: false,
data,
pagination,
});
},
append(data) {
const newData = [...this.value.data, ...data];
this.merge({
isLoading: false,
data: newData,
});
},
prepend(data) {
const newData = [...data, ...this.value.data];
this.merge({
isLoading: false,
data: newData,
});
},
failed(error) {
this.merge({
isLoading: false,
error,
});
},
},
default: {
isLoading: defaultFetching,
data: defaultValue,
error: undefined,
pagination: undefined,
},
});
}exports.fetchingAtom=fetchingAtom;exports.loadingAtom=loadingAtom;exports.openAtom=openAtom;//# sourceMappingURL=helpers.js.map