Guest User

Untitled

a guest
Jul 21st, 2018
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.28 KB | None | 0 0
  1. import { combineReducers } from "redux";
  2.  
  3. const byId = (state = {}, action) => {
  4. switch (action.type) {
  5. case types.CREATE:
  6. case types.UPDATE:
  7. // Note: create and update are the same now so we can let the case for
  8. // create fall through the switch statement to update
  9. const characterData = action.payload;
  10. return { ...state, [id]: characterData };
  11. case types.DELETE:
  12. const { [`${deleteId}`]: deleted, ...newState } = state;
  13. return newState;
  14. default:
  15. return state;
  16. }
  17. };
  18.  
  19. const allIds = (state = [], action) => {
  20. switch (action.type) {
  21. case types.CREATE:
  22. const { id } = action.payload;
  23. return [...state, id];
  24. // Note: we don't need an update here since the ID doesn't change
  25. case types.DELETE:
  26. const deleteId = action.payload;
  27. return state.filter(id => id !== deleteId);
  28. default:
  29. return state;
  30. }
  31. };
  32.  
  33. export const reducer = combineReducers({ byId, allIds });
  34.  
  35. // Note: we'll have to do the UUID work here instead of in the reducer
  36. // so both create reducers have access to the same ID
  37. const createAction = newCharacter => {
  38. // if an ID is passed in, use it, otherwise create a UUID
  39. const id = newCharacter.id || uuid();
  40. return {
  41. type: types.CREATE,
  42. payload: { ...newCharacter, id }
  43. };
  44. };
Add Comment
Please, Sign In to add comment