unistore-hooks

0.1.1 • Public • Published

Unistore Hooks for Preact

Experimental hooks-based bindings for Unistore. Available on npm:

npm i unistore-hooks

Note: this should also work with React, just alias "preact" and "preact/hooks" to "react" in your bundler.

Usage

import { h, render } from 'preact';
import createStore from 'unistore';
import { Provider, useStoreState, useActions } from 'unistore-hooks';

const store = createStore({
  count: 0
});

const ACTIONS = {
  increment({ count }) {
    return { count: count + 1 };
  },
  decrement({ count }) {
    return { count: count - 1 };
  },
  setCount({ }, newCount) {
    return { count: newCount };
  }
};

function App(props) {
  // get state values from the store:
  const { count } = useStoreState('count');
  
  // bind + return all actions:
  const { increment, decrement } = useActions(ACTIONS);

  // or create custom bound actions:
  const { reset, add10 } = useActions(ACTIONS, actions => ({
    reset: () => actions.setCount(0),
    add10: () => actions.increment(10)
  }));

  // or declare parameterized actions:
  const max = props.max || 999;
  const { setToMax } = useActions(ACTIONS, actions => ({
    setToMax: [actions.setCount, max] // equivalent to `actions.setCount(max)`
  }), [max]);
  
  return (
    <div>
      <button onClick={decrement}>-1</button>
      Current value: {count}
      <button onClick={increment}>+1</button>
      <button onClick={reset}>Reset</button>
      <button onClick={setToMax}>Max</button>
    </div>
  );
}

render(
  <Provider value={store}>
    <App />
  </Provider>,
  document.body
);

Readme

Keywords

none

Package Sidebar

Install

npm i unistore-hooks

Weekly Downloads

2

Version

0.1.1

License

none

Unpacked Size

10.4 kB

Total Files

7

Last publish

Collaborators

  • developit