0.0.8 • Published 3 years ago

@maxima/a-store v0.0.8

Weekly downloads
14
License
GPL-3.0-only
Repository
-
Last release
3 years ago

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 store
  • initialState: T - initial store state
  • middlewares: 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

0.0.8

3 years ago

0.0.7

4 years ago

0.0.6

5 years ago

0.0.5

5 years ago

0.0.4

5 years ago

0.0.3

5 years ago

0.0.2

5 years ago

0.0.1

5 years ago