Created
August 9, 2019 18:36
-
-
Save jonasantonelli/4a19a8b0a58d235c0e54df161db850d1 to your computer and use it in GitHub Desktop.
Refactoring Reducer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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