actionsForUser.jsx 1.6 KB

123456789101112131415161718192021222324252627282930313233343536
  1. import { gql } from "../helpers/gql";
  2. import { actionAboutMe } from "./actionAboutMe";
  3. import { actionLeftChat, actionUpdateChat } from "./actionsForChats";
  4. import { actionPromise } from "./actionsPromise";
  5. export const actionUpdateUser = (user) =>
  6. actionPromise('updateUser', gql(`mutation leaveChatByUser($user: UserInput) {
  7. UserUpsert(user: $user) {
  8. login
  9. chats {
  10. title
  11. }
  12. }
  13. }`, {user: user}));
  14. export const actionUpsertUser = (login, nick, password, chatId) =>
  15. async (dispatch, getState) => {
  16. const state = getState();
  17. const currUserId = state.auth?.payload?.sub?.id;
  18. //remove chat from chats array
  19. const chats = chatId ? Object.values(state.chats).filter(chat => chat._id !== chatId).map(chat => {
  20. let {_id} = chat;
  21. //return only id
  22. return {"_id": _id}
  23. })
  24. : null;
  25. const user = Object.fromEntries(Object.entries({_id: currUserId, login, nick, password, chats}).filter(([_, v]) => v != null));
  26. const res = await dispatch(actionUpdateUser(user));
  27. (res && chatId) ?
  28. //actionUpdateChat doesn't work, but it helps to everyone members from the chat to get callback from socket,
  29. // because userUpsert doesn't work from socket
  30. (dispatch(actionLeftChat(state.chats[chatId])) && dispatch(actionUpdateChat({_id: chatId, title: state.chats[chatId].title}))) :
  31. dispatch(actionAboutMe());
  32. }