0.3.0 • Published 6 years ago

@hocs/with-callback-once v0.3.0

Weekly downloads
-
License
MIT
Repository
github
Last release
6 years ago

:bell: with-callback-once

npm ci coverage deps

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.