1.0.0 • Published 8 years ago
react-render-watch v1.0.0
react-render-watch
Declaratively react to state transitions.
*state referring to any combination of React props, state, context, etc...
<Watch
  // The value to watch
  value={props.someValue}
  // test receives current and previous value
  test={(current, prev) => returnsBool(current, prev)}
  // action will be invoked anytime that test returns true
  action={(/* current, prev */) => doSomething()}
/>API
| prop | description | 
|---|---|
| value | The value to watch | 
| test | Function that returns boolean given test(current, prev) | 
| action | Function to be invoked as action(current, prev) when test passes | 
Installation
Install via yarn or npm.
yarn add react-render-watch
// or
npm install --save react-render-watchUsage
Importing Watch
react-render-watch has a single, named export:
// ES6 Modules
import {Watch} from 'react-render-watch';
// CommonJS
const Watch = require('react-render-watch').Watch;
// ...
// Use such as <Watch {...watchProps} />Examples
Request new items when page changes (think pagination).
<Watch
  value={props.currentPage}
  test={(page, prevPage) => page !== prevPage}
  action={page => props.requestPageData(page)}
/>Request data when search criteria changes (think advanced product filtering).
<Watch
  value={makeRequestParams(this.props)}
  test={(params, prevParams) => !_.isEqual(params, prevParams)}
  action={params => requestDataWithParams(params)}
/>React to state changes without requiring a class component for lifecyle methods.
function SomeComponent({text, setText, dangerFlag, setDangerFlag}) {
  return (
    <div>
      <p>Raise the danger flag once input length reaches 5</p>
      <input value={text} onChange={({target: {value}}) => setText(value)} />
      {dangerFlag && (
        <button onClick={() => setDangerFlag(false)}>
          Danger! (click to dismiss)
        </button>
      )}
      <Watch
        value={text}
        test={({length}, previous) => previous.length < 5 && length === 5}
        action={() => setDangerFlag(true)}
      />
    </div>
  );
}