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.
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
);
The
useEffect
import is missing inindex.js
?import { useContext, useMemo, useCallback, useReducer } from 'preact/hooks';
It's used in
useStoreState()
(line49
):useEffect(() => store.subscribe(state => setState(filter(state))), [store]);