Skip to content

Instantly share code, notes, and snippets.

@man27382210
Created March 25, 2018 23:11
Show Gist options
  • Save man27382210/b30c78f67944a598edd64dfd772970e1 to your computer and use it in GitHub Desktop.
Save man27382210/b30c78f67944a598edd64dfd772970e1 to your computer and use it in GitHub Desktop.

Step 1 Normal recompose usage

const { withStateHandlers } = Recompose;

const Counter = ({ count, increment, decrement }) =>
  <div>
    Count: {count} <br />
    <div>
      <button onClick={increment}>+</button>
      <button onClick={decrement}>-</button>
    </div>
  </div>;

const App = withStateHandlers(
  {
    count: 0
  },
  {
    increment: ({ count }) => () => ({ count: count + 1 }),
    decrement: ({ count }) => () => ({ count: count - 1 })
  }
)(Counter);

ReactDOM.render(<App />, document.getElementById("container"));

Step 2 Add one more attr in state

const { withStateHandlers } = Recompose;

const Counter = ({ count, type, increment, decrement }) =>
  <div>
    Count: {count} <br />
    <span>Type: {type}</span>
    <div>
      <button onClick={increment}>+</button>
      <button onClick={decrement}>-</button>
    </div>
  </div>;

const App = withStateHandlers(
  {
    count: 0,
    type: 'hello'
  },
  {
    increment: ({ count }) => () => ({ count: count + 1, type: 'increament' }),
    decrement: ({ count }) => () => ({ count: count - 1, type: 'decrement' })
  }
)(Counter);

ReactDOM.render(<App />, document.getElementById("container"));

Step 3 Use compose

const { withHandlers, withState, compose, pure } = Recompose;

const Counter = ({ count, type, increment, decrement }) =>
  <div>
    Count: {count} <br />
    <span>Type: {type}</span>
    <div>
      <button onClick={increment}>+</button>
      <button onClick={decrement}>-</button>
    </div>
  </div>;

const App = compose(
	withState('count', 'setCounter', 0),
   withState('type', 'setType', 'null'),
	withHandlers({
    increment: ({ setCounter, setType }) => () => {
    	setCounter(n=>n+1)
      setType('increment')
    },
    decrement: ({ setCounter, setType }) => () => {
    	setCounter(n=>n-1)
      setType('decrement')
    }
  }),
  pure
)(Counter);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment