Created
February 8, 2020 20:30
-
-
Save mattisa/bb94dbb29824b25aca9c31bca64b8bd9 to your computer and use it in GitHub Desktop.
Simpe value binder before memoized return values
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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