@maxima/a-store
v0.0.8
Published
Simple frontend state management library for React using TypeScript & React hooks.
Downloads
9
Readme
AStore
Simple frontend state management library for React using TypeScript & React hooks.
How to install
yarn install a-store
How to use
1. Define your store state
interface StoreState {
foo: {
count: number
};
}
const initialState: StoreState = {
foo: { count: 0 }
};
export {
StoreState
};
2. Implement reducer
import { Action, createStore, nestReducers } from 'a-store';
const foo = (state: typeof initialState.foo, action: Action) => {
switch (action.type) {
case 'INC':
return { ...state, count: state.count + 1 };
case 'DEC':
return { ...state, count: state.count - 1 };
default:
return state;
}
};
const reducer = nestReducers<StoreState>({ foo });
3. Create your store and useStore hooks
import { logger } from '@lib/middleware/logger';
const { StoreProvider, useStore } = createStore(reducer, initialState, [logger]);
export {
StoreProvider,
useStore
};
4. Use useStore hook in your components to access current slice of application state and dispatch
function
const Sample: React.SFC<{}> = (props) => {
const [foo, dispatch] = useStore((state) => state.foo);
return (
<div>
{foo.count}
<button type="button" onClick={() => dispatch({ type: 'INC', payload: undefined })}>+</button>
<button type="button" onClick={() => dispatch({ type: 'DEC', payload: undefined })}>-</button>
</div>
);
};
ReactDOM.render(
<StoreProvider>
<Sample />
</StoreProvider>,
document.getElementById('you-name-it')
);
API
createStore(reducer, initialState, middlewares)
reducer: <T>(state: T, action: AnyAction) => T
- reducer function which returns updated state of the storeinitialState: T
- initial store statemiddlewares: Array<Middleware<T, A>>
- array of middleware functions to be added to a dispatch chain
nestReducers(reducerObj)
reducerObj<T, A>: { [K in keyof T]: React.Reducer<T[K], A> }
- plain object of reducers and properties associated with them in a store state
Licence
GPLv3
Copyright hck, 2019