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.
yarn add @hocs/with-callback-once
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);