Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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 the switch statement to 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 }
- };
- };
Add Comment
Please, Sign In to add comment