Skip to content

Instantly share code, notes, and snippets.

@mruhlin
Created October 26, 2018 16:37
Show Gist options
  • Save mruhlin/7397c895688c45f1b09bc0b4d921e11f to your computer and use it in GitHub Desktop.
Save mruhlin/7397c895688c45f1b09bc0b4d921e11f to your computer and use it in GitHub Desktop.
/**
* Loads a DuckEntityForm and pre-populates it with the value from a singleDuck
*
* Note that you need to map the form properties into your component props separately using mapStateToProps. i.e.
*
* const tacos = DuckEntity();
* const tacoForm = DuckEntityForm();
*
* function mapDucksToProps (props) {
* const parentDuck = singleDuck(tacos, props.tacoId);
*
* return: {
* parentDuck,
* formDuck: withForm(parentDuck, tacoForm)
* }
* }
*
* @param entityDuck The entity to be fetched, should be a singleDuck
* @param formDuck The form to be populated
* @param transformLoad Optionally alter model when loading
*/
export const withForm = (entityDuck, formDuck, transformLoad = (model) => model) =>
dependentDuck(entityDuck, ({value, meta}) =>
customDuck(formDuck, {
load: () => dispatch(formDuck.actions.load(transformLoad(value))), // loads the value into RRF
read: (state) => ({
value: state[formDuck.name],
meta: {
...meta,
ready: meta.ready && state[formDuck.name].model.id === value.id // holds off on setting the 'ready' flag until the `formDuck.actions.load` call has finished.
}
})
})
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment