core-native
Version:
A lightweight framework based on React Native + Redux + Redux Saga, in strict TypeScript.
61 lines • 2.04 kB
JavaScript
import { combineReducers } from "redux";
import { Exception, RuntimeException } from "./Exception";
// Redux Action: SetState (to update state.app)
const SET_STATE_ACTION = "@@framework/setState";
export function setStateAction(module, state, type) {
return {
type,
name: SET_STATE_ACTION,
payload: { module, state },
};
}
function setStateReducer(state = {}, action) {
// Use action.name for set state action, make type specifiable to make tracking/tooling easier
if (action.name === SET_STATE_ACTION) {
const { module, state: moduleState } = action.payload;
return { ...state, [module]: { ...state[module], ...moduleState } };
}
return state;
}
export const LOADING_ACTION = "@@framework/loading";
export function loadingAction(show, identifier = "global") {
return {
type: LOADING_ACTION,
payload: { identifier, show },
};
}
function loadingReducer(state = {}, action) {
if (action.type === LOADING_ACTION) {
const payload = action.payload;
const count = state[payload.identifier] || 0;
return {
...state,
[payload.identifier]: count + (payload.show ? 1 : -1),
};
}
return state;
}
// Redux Action: Error (handled by saga)
export const ERROR_ACTION_TYPE = "@@framework/error";
export function errorAction(error) {
if (process.env.NODE_ENV === "development") {
console.warn("Error Caught:", error);
}
const exception = error instanceof Exception ? error : new RuntimeException(error && error.message ? error.message : "unknown error", error);
return {
type: ERROR_ACTION_TYPE,
payload: exception,
};
}
// Root Reducer
export function rootReducer() {
return combineReducers({
loading: loadingReducer,
app: setStateReducer,
});
}
// Helper function, to determine if show loading
export function showLoading(state, identifier = "global") {
return state.loading[identifier] > 0;
}
//# sourceMappingURL=reducer.js.map