Przeglądaj źródła

fixed aboutMe bug && connected localStoreReducer && updated promiseReducer

Ivar 3 lat temu
rodzic
commit
de551e7607

+ 1 - 4
src/App.js

@@ -22,7 +22,6 @@ import {
   actionGetMsgsByChat,
   actionMsgsCount,
 
-  actionAboutMe
 } from "./actions"
 import {store} from "./reducers"
 
@@ -76,9 +75,7 @@ function App() {
   // store.dispatch(actionGetMsgsByChat("61dae9437b27dd2bab6072b6"))
   // store.dispatch(actionMsgsCount("61dae9437b27dd2bab6072b6"))
 
-  useEffect(() => {
-    actionAboutMe()
-  },[])
+
 
   return (
     <Router history={history}>

+ 10 - 35
src/actions/authActions.js

@@ -2,11 +2,13 @@ import {gql} from '../helpers'
 import {   
    actionPromise, 
    actionAuthLogin, 
+   actionAboutMe
 } from '../reducers'
 import {   
    actionUploadFile
 } from './mediaActions'
 
+
  
    const actionLogin = (login, password) => (
       actionPromise('login', gql(`query log($login: String, $password: String) {
@@ -69,6 +71,9 @@ import {
    )
 
 
+
+
+
    // export const actionChangePass = (login, password, newPassword) => (
    //    actionPromise('changePass', gql(`mutation change($login: String! $password: String! $newPassword: String!) {
    //       UserUpsert(user: {login: $login, password: $password, newPassword: $newPassword}) {
@@ -86,38 +91,6 @@ import {
 
 
 
-
-
-
-   const actionUserFindOne = (userId, name='findUserOne') => (
-      actionPromise(name, gql(`query findUserOne($q: String) {
-         UserFindOne (query: $q){
-            _id
-            createdAt
-            login
-            nick
-            avatar {
-               url
-            }
-         }     
-      }`, { 
-            q: JSON.stringify([  {_id: userId}  ])
-         }
-      ))
-   )
-
-
-   export const actionAboutMe = () => (
-      async (dispatch, getState) => {
-         let {auth} = getState()
-         let id = auth?.payload?.sub?.id 
-         if (id) {
-            await dispatch(actionUserFindOne(id, 'myProfile'))
-         }   
-      }
-   )
-
-
    const actionUpdateUser = (userId, avatarId, newLogin, newNick, newChats) => (
       actionPromise('updateUser', gql(`mutation updateUser($user:UserInput) {
          UserUpsert(user:$user) {
@@ -129,7 +102,7 @@ import {
    )
 
       // имеет сомнительную пользу, так как позволяет обновить только аву, 
-      // ниже метод обновляющий логин и ник в форме
+      // ниже метод обновляющий также логин и ник в форме
    export const actionSetAvatar = (name, file) => (
       async (dispatch, getState) => {
          let fileObj = await dispatch(actionUploadFile(name, file))
@@ -143,7 +116,7 @@ import {
       }
    )
 
-   export const actionSetAllUser = (name, file, newLogin, newNick) => (
+   export const actionSetUserInfo = (name, file, newLogin, newNick) => (
       async (dispatch, getState) => {
          let fileObj = await dispatch(actionUploadFile(name, file))
          let {auth} = getState()
@@ -155,9 +128,11 @@ import {
       }
    )
 
+
+      // !!!! ПОДХОД ВЕРНЫЙ ТОЛЬКО ДЛЯ ЗАГРУЗКИ МНОГИХ ФАЙЛОВ В СООБЩЕНИЕ
    // позволяет загрузить файл и взамен получить url  
    // нужен для предпросмотра, когда юзер еще не определился нужно ли добавлять этот url в стейт
-   export const actionSetLocalAvatar = (name, file) => (
+   export const actionGroupFiles = (name, file) => (
       async (dispatch, getState) => {
          let fileObj = await dispatch(actionUploadFile(name, file))
          let URL = fileObj.avatar.url

+ 4 - 4
src/actions/index.js

@@ -2,8 +2,8 @@
 export {
    actionFullLogin, 
    actionFullRegister, 
-   actionAboutMe,
    actionSetAvatar,
+   actionSetUserInfo,
 } from './authActions'
 export {
    actionAddChat, 
@@ -24,9 +24,9 @@ export {
    actionUploadFile,
 } from './mediaActions'
 
-// export {
-//    actionFindUsers
-// } from './findActions'
+export {
+   actionFindUsers
+} from './findActions'
 
 
 

+ 3 - 4
src/components/UserAvatar.js

@@ -13,16 +13,15 @@ export const UserAvatar = ({ profile }) => {
         return '#' + Math.floor(Math.random()*16777215).toString(16);
       }
       let hash = 0;
-      let i;
     
       /* eslint-disable no-bitwise */
-      for (i = 0; i < string?.length; i += 1) {
+      for (let i = 0; i < string?.length; i += 1) {
         hash = string.charCodeAt(i) + ((hash << 5) - hash);
       }
     
       let color = '#';
     
-      for (i = 0; i < 3; i += 1) {
+      for (let i = 0; i < 3; i += 1) {
         const value = (hash >> (i * 8)) & 0xff;
         color += `00${value.toString(16)}`.substr(-2);
       }
@@ -63,5 +62,5 @@ export const UserAvatar = ({ profile }) => {
       </>
    ) 
 }
-export const CUserAvatar = connect(  state => ({profile: state.promise.myProfile?.payload || {}}))(UserAvatar)
+export const CUserAvatar = connect( state => ({profile: state.promise.myProfile?.payload || {}}))(UserAvatar)
 

+ 1 - 1
src/helpers/printStrReq.js

@@ -1,7 +1,7 @@
 
 export const printStrReq = (str, amount) => {
    if (str === undefined) {
-      return 
+      return ''
    } 
    return (str.length >= amount) ? "" : 
    ` минимум ${amount} символ${(((amount[amount.length - 1] == 1) && (amount[amount.length - 2] != 1)) ? '' :

+ 32 - 0
src/reducers/findUserActions.js

@@ -0,0 +1,32 @@
+import {gql} from '../helpers'
+import {
+   actionPromise
+} from './promiseReducer'
+
+export const actionUserFindOne = (userId, name='findUserOne') => (
+   actionPromise(name, gql(`query findUserOne($q: String) {
+      UserFindOne (query: $q){
+         _id
+         createdAt
+         login
+         nick
+         avatar {
+            url
+         }
+      }     
+   }`, { 
+         q: JSON.stringify([  {_id: userId}  ])
+      }
+   ))
+)
+
+
+export const actionAboutMe = () => (
+   async (dispatch, getState) => {
+      let {auth} = getState()
+      let id = auth?.payload?.sub?.id 
+      if (id) {
+         await dispatch(actionUserFindOne(id, 'myProfile'))
+      }   
+   }
+)

+ 4 - 5
src/reducers/index.js

@@ -1,15 +1,12 @@
 // работа со стейтом, подключение редьюсеров, близкие к редьюсерам экшны
 export {
-    promiseReducer,
     actionPromise
 } from './promiseReducer'
 export {
-    authReducer,
     actionAuthLogin, 
     actionAuthLogout
 } from './authReducer'
 export {
-    chatsReducer,
     actionAddListInChats,
     actionAddChatInChats, 
     actionUpdateChatInChats, 
@@ -18,8 +15,10 @@ export {
     actionAddMsgInChat,
     actionUpdateMsgInChat,
 } from './chatsReducer'
-
-export {localStoredReducer} from './localStoredReducer'
+export {
+    actionUserFindOne,
+    actionAboutMe
+} from './findUserActions'
 
 export {store} from './store'
 

+ 20 - 9
src/reducers/promiseReducer.js

@@ -5,15 +5,26 @@ export function promiseReducer(  state={},
    if (!state) {
        return {}
    }
-   if (type === 'PROMISE') {         
-       return {
-           ...state,
-           [name]: {
-               status: status,
-               payload : payload,
-               error: error,
-           }
-       }
+   if (type === 'PROMISE') { 
+        return {
+            ...state, 
+            [name]: {
+                status: status, 
+                payload: (status === 'PENDING' && 
+                                    state[name] && 
+                                    state[name].payload) || 
+                                    payload, 
+                error: error,
+            }
+        }
+        // return {
+        //    ...state,
+        //    [name]: {
+        //        status: status,
+        //        payload : payload,
+        //        error: error,
+        //    }
+        // }
    }
    return state
  }

+ 18 - 15
src/reducers/store.js

@@ -1,29 +1,32 @@
 import {createStore, combineReducers, applyMiddleware} from 'redux'
 import thunk from 'redux-thunk'
-import {promiseReducer} from '../reducers'
-import {authReducer} from '../reducers'
-import {chatsReducer} from '../reducers'
-import {localStoredReducer} from '../reducers'
+import {promiseReducer} from './promiseReducer'
+import {authReducer} from './authReducer'
+import {chatsReducer} from './chatsReducer'
+import {localStoredReducer} from './localStoredReducer'
 
-import {actionAboutMe} from '../actions'
-import * as shoto from '../actions'
+import {actionAboutMe} from './findUserActions'
 
-console.log(shoto)
-// console.log(Object.entries(shoto))
-// debugger;
 
 export const store =  createStore (  combineReducers({ 
-                                          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)
                         )
-console.log(store)
 
-setTimeout(() => store.dispatch(actionAboutMe()), 0)
-// store.dispatch(actionAboutMe())
+// setTimeout(() => store.dispatch(actionAboutMe()), 0)
+store.dispatch(actionAboutMe())
 
 store.subscribe(() => console.log(store.getState()))
 
 
+// combineReducers({cart: localStoredReducer(cartReducer, 'cart'),
+//                  promise: localStoredReducer(promiseReducer, 'promise') })
+//для пользы при работе с промисами надо бы пока PENDING не делать payload undefined 
+//при наличии старого payload 
+//http://gitlab.a-level.com.ua/gitgod/react-template/src/nosaga/src/reducers/index.js#L13