postOne-reducer.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. export const postOneReducer = (state = {}, { type, commentId, newResult, userData = {}, count = null }) => {
  2. const changeComments = (commentList, id, nR, find) =>
  3. commentList.map(c => {
  4. if (c._id === id) {
  5. return { ...c, [find]: nR }
  6. } else if (c?.answers?.length) {
  7. return {
  8. ...c,
  9. answers: changeComments(c.answers, id, nR, find)
  10. }
  11. } else {
  12. return { ...c }
  13. }
  14. })
  15. const types = {
  16. 'POST-ONE-DATA': () => ({ ...newResult }),
  17. 'CLEAR-POST-ONE': () => ({}),
  18. 'POST-ONE-LIKE': () => ({ ...state, likes: [...newResult] }),
  19. 'POST-ONE-ADD-COMMENT': () => ({ ...state, comments: [...newResult] }),
  20. 'UPDATE-COMMENT': () => ({
  21. ...state,
  22. comments: changeComments(state.comments, commentId, newResult, 'answers')
  23. }),
  24. 'EDIT-COMMENT': () => ({
  25. ...state,
  26. comments: changeComments(state.comments, commentId, newResult.text, 'text')
  27. }),
  28. 'LIKE-COMMENT': () => ({
  29. ...state, comments: changeComments(state.comments, commentId, newResult, 'likes')
  30. }),
  31. }
  32. if (type in types) {
  33. return types[type]()
  34. }
  35. return state
  36. }