chat-reducer.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. import jwtDecode from '../../helpers/jwt-decode'
  2. import store from '..';
  3. export default function chatReducer(state = {}, { type, name, status, payload, error, msg, members, user }) {
  4. if (!state) {
  5. return {};
  6. }
  7. if (type === "PROMISE") {
  8. return {
  9. ...state,
  10. [name]: { status, payload, error },
  11. };
  12. }
  13. if (type === "MSG") {
  14. const chat = state.chat?.userData.payload.chats.find(i => i._id === msg.chat._id)
  15. console.log('state', state)
  16. console.log('mssg', msg)
  17. const newState = {
  18. ...state,
  19. userData: {
  20. ...state.userData,
  21. payload: {
  22. ...state.userData.payload,
  23. chats: state.userData.payload.chats.map(item => {
  24. if (item._id === msg.chat._id) {
  25. item.messages = [...item.messages, {
  26. createdAt: msg.createdAt,
  27. media: null,
  28. owner: msg.owner,
  29. text: msg.text,
  30. _id: msg._id
  31. }]
  32. return item
  33. } else return item
  34. })
  35. }
  36. },
  37. };
  38. return newState;
  39. }
  40. if (type === "CHAT") {
  41. if (payload) {
  42. const oldChats = { ...state };
  43. for (const chat of payload) {
  44. const oldChat = oldChats[chat._id];
  45. if (!oldChat) {
  46. oldChats[chat._id] = { ...chat };
  47. }
  48. }
  49. }
  50. return state;
  51. }
  52. if (type === "ADD_USER_CHAT") {
  53. const chat = state.chat?.userData.payload.chats
  54. return {
  55. ...state,
  56. // [chat.members]: { members: members + state[] }
  57. }
  58. }
  59. if (type === "CHAT_CLEAR") {
  60. return {}
  61. }
  62. return state;
  63. }