/flux

A flux utility

Primary LanguageTypeScriptMIT LicenseMIT

@nju33/flux

A Flux utility.

github npm:version typescript ci:status document:typedoc license browserslist

Usage

/**
 * To prepare of using the `Flux`
 * ```sh
 * yarn add @nju33/flux
 * ```
 */
import Flux from '@nju33/flux';

or

<script src="https://unpkg.com/@nju33/flux/flux.js"></script>
<script>
  // Can use the `Flux` here.
</script>

Example by TypeScript

interface State {
  str: string;
  num: number;
  bool: boolean;
}

/**
 * define  in the form of `{[actionName]: payload}`
 */
interface ActionPayload {
  foo: {
    str: State['str'];
  };
  bar: {
    num: State['num'];
  };
  baz: {
    bool: State['bool'];
  };
}

type NameSpace = 'something';

const flux = new Flux<State, ActionPayload, NameSpace>({
  str: '',
  num: -1,
  bool: false,
});

const reducer = flux
  .addAction('foo', (state, payload) => {
    // produce === `immer`
    return produce(state, draft => {
      draft.str = payload.str;
    });
  })
  .addAction('bar', (state, payload) => {
    return produce(state, draft => {
      draft.num = payload.num;
    });
  })
  .addAction(
    'baz',
    (state, payload) => {
      return produce(state, draft => {
        draft.bool = payload.bool;
      });
    },
    // belongs to the 'something' scope
    ['something'],
  )
  .createReducer();

// For example, when using with the Redux.
const store = createStore(reducer);

// By function
store.dispatch(flux.act(({ foo }) => [foo({ str: 'foo' })]));
console.log('1. ', store.getState());

// By curried
const multiAct = flux.act('foo', 'bar');
store.dispatch(multiAct({ str: 'foo2' }, { num: 222 }));
console.log('2. ', store.getState());

// It does not process actions belonging to the 'something' scope
// Thus, `bool` remaining `false`
flux.off('something');
store.dispatch(flux.act(({ baz }) => [baz({ bool: true })]));
console.log('3. ', store.getState());

flux.allOn();
store.dispatch(flux.act(({ baz }) => [baz({ bool: true })]));
console.log('4. ', store.getState());

Edit @nju33/flux

In addition, camelcase-keys and snakecase-keys packages are included in this.

// If they are necessary.
import {camelcaseKeys, snakecaseKeys} from '@nju33/flux';

// ...

store.dispatch(
  flux.act('...')(
    camelcaseKeys({
      /* ... */
    }),
  ),
);