UNPKG

@applicaster/zapp-react-native-utils

Version:

Applicaster Zapp React Native utilities package

61 lines (50 loc) 1.8 kB
import * as R from "ramda"; import { capitalize } from "../../stringUtils"; import { reactUtilsLogger } from "../logger"; const logger = reactUtilsLogger.addSubsystem("CreateContext"); const SETTER_PREFIX = "set"; // this noop function is used temporarily when the React Context is first created export const NOOP = () => {}; /** * gets the setter name for a given property : fooBar => setFooBar * @param property * @returns */ export const getSetterName: (property: string) => string = R.compose( R.concat(SETTER_PREFIX), capitalize ); /** * Creates the setter function for each property, and binds it to the current react component, * invokes the stateValidator if provided in the options * @param properties array of properties for which setters need to be created * @param component react component to which the setter functions must be bound to * @param options * @param options.stateValidator optional Predicate to validate whether * the invokation of the setter is valid or not. It is called with {property, value} * falls back to () => true if not provided */ export function createContextSetters( properties: string[], component: any, options: any = {} ) { const { stateValidator = R.T } = options; R.forEach((property) => { const setterName = getSetterName(property); component[setterName] = (value) => { const oldValue = component.state[property]; if (oldValue === value) { return; } if (stateValidator({ property, value }, oldValue)) { component.setState(R.assoc(property, value)); } else { logger.warning( `trying to invoke ${setterName} with ${value} - but it was rejected by the state validator skipping context update` ); } }; }, properties); }