Skip to content

Instantly share code, notes, and snippets.

@elliotlarson
Last active July 22, 2018 06:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save elliotlarson/effd964a2570cc37fc902d8bd1b23b9e to your computer and use it in GitHub Desktop.
Save elliotlarson/effd964a2570cc37fc902d8bd1b23b9e to your computer and use it in GitHub Desktop.
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