pana-reaction
v0.0.12
Published
A simple wrapper to easily create actions, reducers, and sagas.
Downloads
3
Maintainers
Readme
Reaction
Intention
Reaction wraps Redux and Saga into an simple API so that you can compose a "flow" (action => [reducer] => saga) without all the headache.
Problem
Redux is largely unopinionated when it comes to how you create actions, reducers, and asyncronous actions. On newer projects and projects at scale, it can become cumbersome to write a new "flow" through redux. You create the constant, the action, the reducer, and often an asyncronous action (saga) to go along with your action. If your action requires certain parameters, you have to ensure that those parameters make their way through the entire flow and if something changes, you end up editing all 3 files to make one simple parameter change. That sucks.
Old Way
Too many files to deal with, too many places where your parameters can get lost, too many places to update when you want to change something.
// users/index
import Constants from './constants';
import * as Actions from './actions';
import Reducer from './reducer';
import Sagas from './sagas';
// users/constants.js
export default {
SOME_ACTION: 'USERS/SOME_ACTION',
};
// users/actions.js
import Constants from './constants';
export const someAction = foo => ({
type: Constants.SOME_ACTION,
foo,
});
// users/reducer.js
import Constants from './constants';
const INITIAL_STATE = {
foo: 'bar',
};
export default (state = INITIAL_STATE, action) => {
switch (action.type) {
case Constants.SOME_ACTION:
return {
...state,
foo: action.foo,
};
default:
return state;
}
};
// users/sagas.js
import regeneratorRuntime from 'regenerator-runtime';
import { put } from 'redux-saga/effects';
import Constants from './constants';
function* someAction(action) {
try {
let { foo } = action;
// Some saga logic here
} catch (e) {}
}
export function* watchSomeAction() {
yield takeEvery(Constants.SOME_ACTION, someAction);
}
export default all([fork(watchSomeAction)]);
The Reaction Way
// users/index.js
import Reaction from 'pana-reaction';
const users = new Reaction({
name: 'users',
initialState: {
foo: 'bar',
},
});
// This "flow" can even be extracted to it's own file! See the examples below.
const someActionFlow = users.createFlow(
// Action name which turns into the constant name
'someAction',
// The Dispatchable Action
({ foo }) => ({ foo }),
// The reducer
(state, action) => ({
...state,
foo: action.foo,
}),
// Additional Reaction Options
{
requiredParams: ['foo'],
}
);
users.createSaga(someActionFlow.constant, function*(action) {
try {
let { foo } = action;
// Some saga logic here
} catch (e) {}
});
export default users;
Installation and Use
$ npm install --save pana-reaction
import Reaction from 'pana-reaction';
const someReaction = new Reaction({ name: 'reaction' });
export default someReaction;
API
createFlow(name, [action], [reducer], [options])
Arguments
name
(String || NameObject): This parameter is the only required argument in createFlow. Using the name, createFlow will generate a simple action creator that you can pass around just like a normal redux action. Name can be a simple string, or a custom NameObject- NameString
- Name will be used as the action funciton name and will be
- NameObject
actionName
: (String) will turn into the action function nameconstant
: (String) will become the action type[merge]
: (Boolean) optional, defaults to false. If true, the constant will get combined with the Reaction name like the default behavior when you pass in a name string. If false, the true constant value that you pass in will be used.
- NameString
const example = new Reaction({ name: 'example' });
example.createFlow('someFlow');
//... some other file
example.Actions.someFlow();
/*
returns => {
type: 'EXAMPLE/SOME_FLOW',
}
*/
[action]
(Function): The action creator. Actions can only have one parameter and will be merged directly with the action type. Any additional parameters will be ignored.
Taken directly from Redux documentation: Actions are payloads of information that send data from your application to your store. They are the only source of information for the store. You send them to the store using store.dispatch().
example.createFlow('someFlow', ({ foo, bar }) => ({ foo, bar }));
//... some other file
example.Actions.someFlow({ foo: 'foo', bar: 'bar' });
/*
returns => {
type: 'EXAMPLE/SOME_FLOW',
foo: 'foo',
bar: 'bar,
}
*/
[reducer]
(Function): A reducer function takes two parameters(state, action)
and should return a slice of that reducers state. You can read Redux's Reusing Reducer Logic to understand the inspiration behind this (Reaction implementscreateReducer
behind the scenes).
example.createFlow(
'someFlow',
({ foo, bar }) => ({ foo, bar }),
(state, action) => ({
...state,
foo: action.foo,
bar: action.bar,
})
);
//... some other file
// Given the initial state...
initialState = {
bang: 'bang',
foo: null,
bar: null,
};
// After calling
store.dispatch(example.Actions.someFlow({ foo: 'foo', bar: 'bar' }));
// Next state will look like
nextState = {
bang: 'bang',
foo: 'foo',
bar: 'bar',
};
[options]
(Object)requiredParams
(Array[String]): This option allows you to "soft" validate params getting passed into your action. It takes an array of strings which can be dot-notated to reach nested values. It will validate similarly to propTypes, throwing a console warning instead of a true error, and won't stop code execution. e.g.requiredParams: ['foo', 'bar.bang', 'some.nested[0].value']
Return Value
createFlow returns all of the internally used values, allowing you to pass these around as you need.
{
actionName,
action,
reducer,
constant
}
Example
const foo = example.createFlow('foo');
console.log(foo.actionName); // 'foo'
console.log(foo.action); // (Wrapped Action Function) foo.action() => {type: 'TEST/FOO'}
console.log(foo.reducer); // Exact value passed into createFlow
console.log(foo.constant); // 'TEST/FOO'