@hocs/with-callback-once
v0.3.0
Published
Invokes a callback once condition is true as a HOC for React and React Native
Downloads
1
Maintainers
Readme
:bell: with-callback-once
Part of a collection of Higher-Order Components for React, especially useful with Recompose.
Invokes a callback once condition is true (while previous check was false), useful to decouple side effects like onSuccess
or onError
handlers in a declarative way.
Install
yarn add @hocs/with-callback-once
Usage
withCallbackOnce(
shouldCall: (props: Object) => boolean,
callback: (props: Object) => void
): HigherOrderComponent
import React from 'react';
import { compose, withState, withHandlers } from 'recompose';
import withCallbackOnChangeWhile from '@hocs/with-callback-on-change-while';
import withCallbackOnce from '@hocs/with-callback-once';
const Demo = ({ count, onButtonClick }) => (
<div>
<h1>{count}</h1>
<button onClick={onButtonClick}>decrement</button>
</div>
);
export default compose(
withState('count', 'setCount', 5),
withHandlers({
onButtonClick: ({ setCount, count }) => () => setCount(count - 1)
}),
withCallbackOnChangeWhile(
'count',
({ count }) => count >= 0,
({ count }) => console.log(count)
),
withCallbackOnce(
({ count }) => count === 0,
() => console.log('done!')
)
)(Demo);
:tv: Check out live demo.