UNPKG

@mongez/react-atom

Version:

A simple state management tool for React Js.

106 lines (105 loc) 2.77 kB
import {atom}from'./react-atom.js';/** * Create a boolean atom */ function openAtom(key, defaultOpened = false) { return 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 = 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 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, }, }); }export{fetchingAtom,loadingAtom,openAtom};//# sourceMappingURL=helpers.js.map