Skip to content

Instantly share code, notes, and snippets.

@mattisa
Created February 8, 2020 20:30
Show Gist options
  • Save mattisa/bb94dbb29824b25aca9c31bca64b8bd9 to your computer and use it in GitHub Desktop.
Save mattisa/bb94dbb29824b25aca9c31bca64b8bd9 to your computer and use it in GitHub Desktop.
Simpe value binder before memoized return values
import { get, set, isEqual } from 'lodash';
import deepClone from 'clone-deep';
const defaultOpts = {
parseValue: (v: any) => v,
parseState: (v: any) => v,
valueFn: 'value',
onChangeFn: 'onChange'
};
export default function bindState(data: object, setData: (newState: object) => void) {
return function componentArgs(key: string, opts = {}) {
const options = {
...defaultOpts,
...opts
};
function onChange() {
const newState = deepClone(data);
const newValue = deepClone(options.parseState.apply(this, Array.from(arguments)));
set(newState, key, newValue);
if (!isEqual(newState, data)) {
setData(newState);
}
}
const value = options.parseValue(get(data, key));
return {
[options.valueFn]: value,
[options.onChangeFn]: onChange
};
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment