Skip to content

Instantly share code, notes, and snippets.

@bultas
Last active June 26, 2019 19:04
Show Gist options
  • Save bultas/3424e19025d57f5f9ed412efec06702d to your computer and use it in GitHub Desktop.
Save bultas/3424e19025d57f5f9ed412efec06702d to your computer and use it in GitHub Desktop.
Redux-Loop Reducer boilerplate
/// @ts-check
import { loop, Cmd } from 'redux-loop';
import { error } from 'lib/result';
import { fetchItem } from 'effects/itemEffects';
import { ITEM_LOCATION } from 'constants/routerConstants';
const initState = {
fetching: null,
data: error()
};
const ITEM_RECEIVED_SUCCESS = 'ITEM_RECEIVED_SUCCESS';
const ITEM_RECEIVED_ERROR = 'ITEM_RECEIVED_ERROR';
export const fetchItemSuccess = () => ({ type: ITEM_RECEIVED_SUCCESS });
export const fetchItemError = () => ({ type: ITEM_RECEIVED_ERROR });
const createFetchLoop = (state, _action) =>
loop(
{ ...state, fetching: true },
Cmd.run(fetchItem, {
successActionCreator: fetchItemSuccess,
failActionCreator: fetchItemError
})
);
export function itemReducer(state = initState, action = {}) {
switch (action.type) {
case ITEM_LOCATION: {
return createFetchLoop(state, action);
}
case ITEM_RECEIVED_SUCCESS: {
console.log(ITEM_RECEIVED_SUCCESS);
return state;
}
default:
return state;
}
}
/// @ts-check
import { loop, Cmd } from 'redux-loop';
import assert from 'assert';
import { error } from 'lib/result';
import { ITEM_LOCATION } from 'constants/routerConstants';
import { fetchItem } from 'effects/itemEffects';
import { itemReducer, fetchItemSuccess, fetchItemError } from './itemReducer';
const createState = ({ fetching = null, data = error() } = {}) => ({
fetching,
data
});
describe('itemReducer', () => {
it('Init state', () => {
const actual = itemReducer();
const expected = createState();
assert.deepEqual(actual, expected);
});
it('ITEM_LOCATION', () => {
const actual = itemReducer(undefined, { type: ITEM_LOCATION });
const expected = loop(
createState({ fetching: true }),
Cmd.run(fetchItem, {
successActionCreator: fetchItemSuccess,
failActionCreator: fetchItemError
})
);
assert.deepEqual(actual, expected);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment