Skip to content
This repository has been archived by the owner on Jul 8, 2023. It is now read-only.

Latest commit

 

History

History

with-callback-once

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 
 
 
 
 
 
 

🔔 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);

📺 Check out live demo.