More HOCs with Recompose

lifecycle with timeout toggle

by jonahe

HTML

<script src="https://unpkg.com/[email protected]/dist/react-with-addons.js"></script>
<script src="https://unpkg.com/[email protected]/dist/react-dom.js"></script>
<script src="https://unpkg.com/[email protected]/build/Recompose.js"></script>
<div id="root"></div>

Babel + JSX

const { compose, withStateHandlers, branch, lifecycle } = Recompose;

const withNamedToggler = (propertyNameBase, initialValue) => withStateHandlers(
	{ [`${propertyNameBase}IsToggled`] : initialValue },
  {
  	[`${propertyNameBase}Toggler`] : props => (e) => {
    		return { [`${propertyNameBase}IsToggled`]: !props[`${propertyNameBase}IsToggled`] };
    }
  }
);

const withTimeoutToggle = (propertyNameBase, initialValue, duration) => {
  return compose(
  	withNamedToggler(propertyNameBase, initialValue),
    lifecycle({ 
    	componentDidMount() {
        const propertyTogglerName = `${propertyNameBase}Toggler`;
        setTimeout(this.props[propertyTogglerName], duration)
      },
      componentWillUnmount() {
      	
      } 
    })
  );
};

const withMyThingTimeoutToggler = withTimeoutToggle("myThing", true, 2000);

const Simple = (props) => {
	console.log(props)
	return (
  	<div>
    	{ props.myThingIsToggled ? <h1>Hello</h1> : <h1>Goodbye</h1> }
    </div>
  );
};

const SimpleWithState = withMyThingTimeoutToggler(Simple)

const App = () => {
  return (
  	<div>
      <SimpleWithState />
    </div>
  );
};

ReactDOM.render(<App />, document.getElementById('root'));