UNPKG

core-native

Version:

A lightweight framework based on React Native + Redux + Redux Saga, in strict TypeScript.

90 lines 3.24 kB
import { app } from "../app"; import { produce, enablePatches } from "immer"; import { setStateAction } from "../reducer"; if (process.env.NODE_ENV === "development") { enablePatches(); } export class Module { constructor(name, initialState) { this.name = name; this.initialState = initialState; } *onEnter(routeParameters) { /** * Called when the attached component is mounted. * The routeParameters is auto specified if the component is connected to React Navigator. * Otherwise, routeParameters will be {}. */ } *onDestroy() { /** * Called when the attached component is going to unmount. */ } *onTick() { /** * Called periodically during the lifecycle of attached component. * Usually used together with @Interval decorator, to specify the period (in second). * Attention: The next tick will not be triggered, until the current tick has finished. */ } *onAppActive() { /** * Called when the app becomes active (foreground) from background task. * Usually used for fetching updated configuration. */ } *onAppInactive() { /** * Called when the app becomes inactive (background) from foreground task. * Usually used for storing some data into storage. */ } *onFocus() { /** * Called when the attached component is connected to navigator, and gets focused. * React Navigation Required: 5.x */ } *onBlur() { /** * Called when the attached component is connected to navigator, and gets blurred. * React Navigation Required: 5.x */ } get state() { return this.rootState.app[this.name]; } get rootState() { return app.store.getState(); } get logger() { return app.logger; } setState(stateOrUpdater) { if (typeof stateOrUpdater === "function") { const originalState = this.state; const updater = stateOrUpdater; let patchDescriptions; // TS cannot infer RootState["app"][ModuleName] as an object, so immer fails to unwrap the readonly type with Draft<T> const newState = produce(originalState, (draftState) => { // Wrap into a void function, in case updater() might return anything updater(draftState); }, process.env.NODE_ENV === "development" ? (patches) => { // No need to read "op", in will only be "replace" patchDescriptions = patches.map((_) => _.path.join(".")); } : undefined); if (newState !== originalState) { const description = `@@${this.name}/setState${patchDescriptions ? `[${patchDescriptions.join("/")}]` : ``}`; app.store.dispatch(setStateAction(this.name, newState, description)); } } else { const partialState = stateOrUpdater; this.setState((state) => Object.assign(state, partialState)); } } } //# sourceMappingURL=Module.js.map