Przeglądaj źródła

done update user profile

Ivar 3 lat temu
rodzic
commit
c4c2c57fa6

+ 11 - 6
src/actions/authActions.js

@@ -91,14 +91,14 @@ import {
 
 
 
-   const actionUpdateUser = (userId, avatarId, newLogin, newNick, newChats) => (
+   const actionUpdateUser = (userId, newLogin, newNick, avatarId, newChats) => (
       actionPromise('updateUser', gql(`mutation updateUser($user:UserInput) {
          UserUpsert(user:$user) {
             _id   
             login  
             nick
          }
-      }`, { user: {_id: userId, avatar: {_id: avatarId} } }))
+      }`, { user: {_id: userId, login: newLogin, nick: newNick, avatar: {_id: avatarId} } }))
    )
 
       // имеет сомнительную пользу, так как позволяет обновить только аву, 
@@ -118,12 +118,17 @@ import {
 
    export const actionSetUserInfo = (name, file, newLogin, newNick) => (
       async (dispatch, getState) => {
-         let fileObj = await dispatch(actionUploadFile(name, file))
-         let {auth} = getState()
-         let userId = auth?.payload?.sub?.id 
+         let {promise} = getState()
+         let {_id: userId, avatar: {_id: avatarId} } = promise.myProfile?.payload
 
-         await dispatch(actionUpdateUser(userId, fileObj._id, newLogin, newNick))
+         console.log(userId, file, avatarId, newLogin, newNick)
 
+         if (file) {
+            let fileObj = await dispatch(actionUploadFile(name, file))
+            await dispatch(actionUpdateUser(userId, newLogin, newNick, fileObj?._id))
+         } else {
+            await dispatch(actionUpdateUser(userId, newLogin, newNick, avatarId))
+         }
          await dispatch(actionAboutMe())    
       }
    )

+ 0 - 1
src/actions/mediaActions.js

@@ -17,7 +17,6 @@ export const actionUploadFile = (name, file) => {
 }
 
     
-
 // MediaUpsert нужен только для добавления данных для загруженного файла
 // и дальнейшего отображения его через эти данные (через аватары, сообщения)
 // const actionChangeFile = (mediaId) => (

+ 38 - 44
src/components/ProfileModal.js

@@ -1,4 +1,4 @@
-import React, {useEffect, useState} from 'react';
+import React, {useEffect, useState, useRef} from 'react';
 import Box from '@mui/material/Box';
 import Modal from '@mui/material/Modal';
 import MenuItem from '@mui/material/MenuItem';
@@ -14,7 +14,7 @@ import {UserAvatar} from '../components'
 
 import { printStrReq } from "../helpers";
 import {connect}  from 'react-redux'
-import {actionSetAvatar} from '../actions'
+import {actionSetUserInfo} from '../actions'
 
 
 const styleModalParrent = {
@@ -34,33 +34,6 @@ const styleModalParrent = {
 }
 
 
-const AvatarDropZone = ({onLoad}) => {
-   const {
-      acceptedFiles,
-      getRootProps,
-      getInputProps
-    } = useDropzone({   
-      accept: 'image/*', 
-      maxFiles: 1,
-      onDrop: (acceptedFiles) => {
-         console.log(acceptedFiles[0])
-         // onLoad("media", acceptedFiles[0])
-      }
-    });
-   
-   return (
-      <form action="/upload" method="post" encType="multipart/form-data" id='formUser'> 
-         <section className="container">
-            <div {...getRootProps({className: 'dropzone'})}>
-               <input {...getInputProps()} type="file" name="media" id='mediaUser' />
-               <p>Изменить аватар</p>
-            </div>
-         </section>
-      </form>
-   );
-}
-const CAvatarDropZone = connect( null, {onLoad: actionSetAvatar})(AvatarDropZone)
-
 
 
 const ProfileModal = ({minLog='2', myProfile, onСonfirm, onModalOpen}) => {
@@ -68,20 +41,30 @@ const ProfileModal = ({minLog='2', myProfile, onСonfirm, onModalOpen}) => {
    // console.log(myProfile)
   // const {login, nick, avatar: {url}} = myProfile
 
-  const [login, setLogin] = useState(myProfile.login)
-  const [logBlur, setLogBlur] = useState(false)
-
-  const [nick, setNick] = useState(myProfile.nick)
-
-  const [img, setImg] = useState(myProfile.avatar?.url)
+   const [login, setLogin] = useState(myProfile.login)
+   const [logBlur, setLogBlur] = useState(false)
+   const [nick, setNick] = useState(myProfile.nick)
+   const currAvatar = useRef(myProfile.avatar?.url)
 
+   const [img, setImg] = useState(null)
+   const {
+      acceptedFiles,
+      getRootProps,
+      getInputProps
+   } = useDropzone({   
+      accept: 'image/*', 
+      maxFiles: 1,
+      onDrop: (acceptedFiles) => {
+         console.log(acceptedFiles)
+         setImg(acceptedFiles[0])
+      }
+   });
 
-  const handleOpen = () => {setOpen(true)}
-  const handleClose = () => {setOpen(false)}
+  const handleOpen = () => setOpen(true)
+  const handleClose = () => (setImg(null), setOpen(false))
 
   return (
     <div>
-      {/* <Button onClick={handleOpen}>Профиль</Button> */}
       <MenuItem onClick={handleOpen}>
                Профиль
       </MenuItem>
@@ -105,10 +88,21 @@ const ProfileModal = ({minLog='2', myProfile, onСonfirm, onModalOpen}) => {
                   Мой профиль
                </Typography>
             </Box>
-
+            
             <Box sx={{ display: 'flex', justifyContent: 'start', mt: 2,  }}>
-               <UserAvatar profile={{login: login, nick: nick, avatar: {url: img || ''}}} />
-               <CAvatarDropZone />
+
+               <UserAvatar profile={{  login: login, nick: nick, avatar: {url: myProfile.avatar?.url || ''},
+                                       localUrl: img && URL.createObjectURL(img)}} />
+
+               <form action="/upload" method="post" encType="multipart/form-data" id='formUser'> 
+                  <section className="container">
+                     <div {...getRootProps({className: 'dropzone'})}>
+                        <input {...getInputProps()} type="file" name="media" id='mediaUser' />
+                        <p>Изменить аватар</p>
+                     </div>
+                  </section>
+               </form>
+
             </Box>
 
             <Box sx={{ display: 'flex', flexDirection: 'column', justifyContent: 'center', mt: 4 }}>
@@ -147,7 +141,7 @@ const ProfileModal = ({minLog='2', myProfile, onСonfirm, onModalOpen}) => {
             </Box>
             
             <Box sx={{ display: 'flex', flexDirection: 'column', justifyContent: 'center', mt: 4 }}>
-               <Typography variant="body1" /* color="error" */>
+               <Typography variant="body1" >
                   Изменить ник
                </Typography>
                <TextField  
@@ -178,7 +172,7 @@ const ProfileModal = ({minLog='2', myProfile, onСonfirm, onModalOpen}) => {
             <Box sx={{ display: 'flex', justifyContent: 'end', mt: 2}}>
                <Button  variant="contained" 
                         disabled={(login?.length >= minLog) ? false : true}
-                        onClick={() => onСonfirm()}>
+                        onClick={() => onСonfirm("media", img, login, nick)}>
                   Применить 
                </Button>
             </Box>
@@ -190,6 +184,6 @@ const ProfileModal = ({minLog='2', myProfile, onСonfirm, onModalOpen}) => {
   );
 }
 export const CProfileModal = connect(  state => ({myProfile: state.promise?.myProfile?.payload || {}}), 
-                                       {onСonfirm : actionSetAvatar})(ProfileModal)
+                                       {onСonfirm : actionSetUserInfo})(ProfileModal)
 
 

+ 19 - 2
src/components/UserAvatar.js

@@ -35,7 +35,12 @@ export const UserAvatar = ({ profile }) => {
         return 
       }
       let titleStr = ''
+      let letterAmount = 2
       for (const word of str.split(' ')) {
+        if (letterAmount <= 0) {
+          break
+        }
+        letterAmount--
         if (word) {
           titleStr += word[0].toUpperCase()
         }  
@@ -52,11 +57,23 @@ export const UserAvatar = ({ profile }) => {
       };
     }
 
+
+    function getUrl() {
+      if (profile.localUrl) {
+        return profile.localUrl
+      } else if (profile.avatar?.url) {
+        return backURL + profile.avatar?.url
+      } else {
+        return null
+      }
+    }
+
+
    return (
       <>
       {
-         profile.avatar?.url ?
-         <Avatar alt={profile.nick || profile.login } src={backURL + profile.avatar?.url} /> :
+         !!getUrl() ?
+         <Avatar alt={profile.nick || profile.login } src={getUrl()} /> :
          <Avatar  {...stringAvatar(profile.nick || profile.login)} /> 
       }        
       </>

+ 1 - 0
src/reducers/findUserActions.js

@@ -11,6 +11,7 @@ export const actionUserFindOne = (userId, name='findUserOne') => (
          login
          nick
          avatar {
+            _id
             url
          }
       }     

+ 6 - 7
src/reducers/store.js

@@ -9,17 +9,16 @@ import {actionAboutMe} from './findUserActions'
 
 
 export const store =  createStore (  combineReducers({ 
-                                    promise: localStoredReducer(promiseReducer, 'promise'),
-                                    auth: localStoredReducer(authReducer, 'auth'),
-                                    chats: localStoredReducer(chatsReducer, 'chats'),
-                                    // promise: promiseReducer, 
-                                    // auth: authReducer, 
-                                    // chats: chatsReducer
+                                    // promise: localStoredReducer(promiseReducer, 'promise'),
+                                    // auth: localStoredReducer(authReducer, 'auth'),
+                                    // chats: localStoredReducer(chatsReducer, 'chats'),
+                                    promise: promiseReducer, 
+                                    auth: authReducer, 
+                                    chats: chatsReducer
                                                 }),
                                     applyMiddleware(thunk)
                         )
 
-// setTimeout(() => store.dispatch(actionAboutMe()), 0)
 store.dispatch(actionAboutMe())
 
 store.subscribe(() => console.log(store.getState()))