Skip to content

Instantly share code, notes, and snippets.

@jonasantonelli
Created August 9, 2019 18:36
Show Gist options
  • Save jonasantonelli/4a19a8b0a58d235c0e54df161db850d1 to your computer and use it in GitHub Desktop.
Save jonasantonelli/4a19a8b0a58d235c0e54df161db850d1 to your computer and use it in GitHub Desktop.
Refactoring Reducer
import schema from './schema';
import { ACTIONS } from './action';
const fetching = substate => (state, action) => {
return {
...state,
[substate]: {
...state[substate],
...action.value,
fetching: true
}
};
};
const fetchComplete = substate => (state, action) => {
return {
...state,
[substate]: {
...state[substate],
value: action.value,
fetching: false
}
};
};
const unselectItem = (state) => {
return {
...state,
selected: {
fetching: false,
value: {}
}
};
}
const posting = (state) => {
return {
...state,
selected: {
posting: true
}
};
}
const postComplete = (state) => {
return {
...state,
selected: {
posting: false
}
};
}
const error = (state, action) => {
return {
...state,
isError: true,
errorMessage: action.errorMessage
};
}
const commands = {
[ACTIONS.FETCHING_LIST]: fetching('list'),
[ACTIONS.FETCHING_HEADER]: fetching('header'),
[ACTIONS.FETCHING_ITEM]: fetching('selected'),
[ACTIONS.FETCH_LIST_COMPLETE]: fetchComplete('list'),
[ACTIONS.FETCH_HEADER_COMPLETE]: fetchComplete('header'),
[ACTIONS.FETCH_ITEM_COMPLETE]: fetchComplete('selected'),
[ACTIONS.UNSELECT_ITEM]: unselectItem,
[ACTIONS.POSTING]: posting,
[ACTIONS.ERROR]: error,
[ACTIONS.CREATED]: postComplete,
[ACTIONS.UPDATED]: postComplete
};
export default (state = schema, action) => {
const command = commands[action.type];
if (!command) return state;
return command(state, action);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment