Created
March 6, 2018 15:48
-
-
Save ddombrow/03cd50ab51a8bebf95a88edbe008640d to your computer and use it in GitHub Desktop.
HOC and render prop component with memoization to convert immutable props to JS props.
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 { Iterable } from "immutable"; | |
import memoize from "fast-memoize"; | |
function deImmutable(immutableProps) { | |
const KEY = 0; | |
const VALUE = 1; | |
return Object.entries( | |
immutableProps | |
).reduce((newProps, wrappedComponentProp) => { | |
newProps[wrappedComponentProp[KEY]] = Iterable.isIterable( | |
wrappedComponentProp[VALUE] | |
) | |
? wrappedComponentProp[VALUE].toJS() | |
: wrappedComponentProp[VALUE]; | |
return newProps; | |
}, {}); | |
} | |
const deImmutableMemoized = memoize(deImmutable); | |
// HOC version | |
/* eslint-disable react/display-name */ | |
export function withImmutable(ComponentWithImmutable) { | |
return wrappedProps => (<ComponentWithImmutable {...deImmutableMemoized(wrappedProps)} />); | |
} | |
/* eslint-enable */ | |
// Render Prop version | |
export class WithImmutable extends React.Component { | |
constructor(props) { | |
super(props); | |
} | |
render() { | |
return this.props.render(deImmutableMemoized(this.props)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment