Last active
June 30, 2022 21:59
-
-
Save crcn/d487e43b78260d21b7bcbf8edd54b0ca to your computer and use it in GitHub Desktop.
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
// there are many ways to massage this to look prettier, but this | |
// essentially is a pure JS side-effect engine. | |
// API passed in like this so that we can test the engine. | |
const GroceryListEngine = (api) => (dispatch, initialState) => { | |
// all side-effect functions take an event, do one thing, then | |
// dispatch a new event. | |
const createListItem = ({payload:{text}}) => { | |
api.addListItem(text) | |
.then((newListItem) => { | |
dispatch(actions.listItemCreated(newListItem)) | |
}) | |
.catch(error) => { | |
dispatch(actions.newListItemFailedToCreate(error)) | |
}) | |
} | |
const reloadListItems = () => { | |
api.reloadList() | |
.then((newListItem) => { | |
dispatch(actions.listItemCreated(newListItem)) | |
}) | |
.catch(error) => { | |
dispatch(actions.newListItemFailedToCreate(error)) | |
}) | |
} | |
return (action, currState, prevState) => { | |
// orchestrates what gets called when events occur in the app. | |
switch(action.type) { | |
case "USER_SUBMITTED_LIST_ITEM": { | |
createListItem(action); | |
break; | |
} | |
case "REFRESH_LIST_ITEMS_BUTTON_CLICKED": | |
case "LIST_ITEM_CREATED": { | |
reloadListItems(); | |
break; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment