1.3.0 • Published 5 years ago
@nju33/flux v1.3.0
@nju33/flux
A Flux utility.
Usage
/**
* To prepare of using the `Flux`
* ```bash
* 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());
Tips / I want to define a action which have not payload nothing.
You should use void
as type of payload. Here is an example.
interface ActionPayload {
voidIncrement: void;
undefinedIncrement: undefined;
}
// ...
flux.act(({voidIncrement}) => [
increment(),
// Expected 1 arguments, but got 0.
// undefinedIncrement(),
undefinedIncrement(undefined),
]);
Very useful functions
In addition, camelcase-keys and snakecase-keys packages are included in this, because it is used a lot.
// If they are necessary.
import {camelcaseKeys, snakecaseKeys} from '@nju33/flux';
// ...
store.dispatch(
flux.act('...')(
camelcaseKeys({
/* ... */
}),
),
);