-
-
Save elliotlarson/effd964a2570cc37fc902d8bd1b23b9e to your computer and use it in GitHub Desktop.
This file contains hidden or 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 { combineReducers } from "redux"; | |
const byId = (state = {}, action) => { | |
switch (action.type) { | |
case types.CREATE: | |
case types.UPDATE: | |
// Note: create and update are the same now so we can let the case for | |
// create fall through to the case for update | |
const characterData = action.payload; | |
return { ...state, [id]: characterData }; | |
case types.DELETE: | |
const { [`${deleteId}`]: deleted, ...newState } = state; | |
return newState; | |
default: | |
return state; | |
} | |
}; | |
const allIds = (state = [], action) => { | |
switch (action.type) { | |
case types.CREATE: | |
const { id } = action.payload; | |
return [...state, id]; | |
// Note: we don't need an update here since the ID doesn't change | |
case types.DELETE: | |
const deleteId = action.payload; | |
return state.filter(id => id !== deleteId); | |
default: | |
return state; | |
} | |
}; | |
export const reducer = combineReducers({ byId, allIds }); | |
// Note: we'll have to do the UUID work here instead of in the reducer | |
// so both create reducers have access to the same ID | |
const createAction = newCharacter => { | |
// if an ID is passed in, use it, otherwise create a UUID | |
const id = newCharacter.id || uuid(); | |
return { | |
type: types.CREATE, | |
payload: { ...newCharacter, id } | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment