unknown il y a 2 ans
Parent
commit
ec8dafbc5d

Fichier diff supprimé car celui-ci est trop grand
+ 1 - 1
.eslintcache


+ 15 - 5
src/App.tsx

@@ -2,11 +2,11 @@ import { lazy, Suspense } from 'react';
 import { BrowserRouter, Switch } from 'react-router-dom';
 import { ToastContainer } from 'react-toastify';
 import { useEffect } from 'react';
-import { useSelector } from 'react-redux';
+import { useSelector, useDispatch } from 'react-redux';
 
 import s from './App.module.css';
 import { getToken } from './redux/authorization/selector'
-import { setToken } from './api-data'
+import {asyncLogout} from './redux/authorization/operations'
 import PrivateRoute from './components/Routes/PrivateRoute/PrivateRoute';
 import PublicRoute from './components/Routes/PublicRoute/PublicRoute';
 import Loader from './components/Loader/Loader';
@@ -24,9 +24,19 @@ const AuthPage = lazy(
 
 function App() {
   const token = useSelector(getToken)
+  const dispatch = useDispatch()
+
+  useEffect(() => {
+    if(!localStorage.isChecked) localStorage.isChecked = 'true'
+  }, [])
+
   useEffect(() => {
-    if (localStorage.isChecked&&token) setToken.set(token)
-  }, [token])
+    const handleKeepIn = () => {
+     if (localStorage.isChecked === 'false') dispatch(asyncLogout())
+    }
+    window.addEventListener("beforeunload",handleKeepIn)
+    return () => window.removeEventListener("beforeunload",handleKeepIn)
+  }, [dispatch,token])
 
   return (
     <div className={s.appWrapper}>
@@ -36,7 +46,7 @@ function App() {
             <PrivateRoute exact path="/">
               Home
             </PrivateRoute>
-              <PublicRoute exact path={'/z/'} restricted>
+              <PublicRoute  path={'/z/'} restricted>
                 <AuthPage />
               </PublicRoute>
           </Switch>

+ 6 - 4
src/api-data/index.ts

@@ -53,19 +53,21 @@ const loginUser = async <T>(number:string,code:string):Promise<T | undefined> =>
   }
 };
 
-const updateCredentials = async (name: string,lastName: string):Promise<void> => {
+const updateCredentials = async (name: string,lastName: string):Promise<any> => {
   try {
-    await axios.patch('/users/current', { name, lastName });
+    const { data : {data} } = await axios.patch('/users/current', { name, lastName });
     success(`CREDENTIALS UPDATED`);
+    return data
   } catch (e) {
     error('BAD REQUEST');
   }
 };
 
-const updateUserAvatar = async (file: object):Promise<void> => {
+const updateUserAvatar = async (formData: any): Promise<any> => {
   try {
-    await axios.patch('/users/avatar', file);
+    const { data : {data} } = await axios.patch('/users/avatars', formData);
     success(`AVATAR UPDATED`);
+    return data
   } catch (e) {
     error('BAD REQUEST');
   } 

+ 5 - 5
src/components/AuthPage/Registration/index.tsx

@@ -35,7 +35,7 @@ const Registration = () => {
   const classes = useStyles()
   const [name, setName] = useState<string>('')
   const [lastName, setLastName] = useState<string>('')
-  const [upload, setUpload] = useState<object | null>(null)
+  const [upload, setUpload] = useState<any>(null)
   const dispatch = useDispatch()
   const format = (a: string) => a.split(' ').join('').trim()
 
@@ -63,10 +63,10 @@ const Registration = () => {
     }
   }
 
-  const handleUpdateUser = async() => {
-    upload&&dispatch(asyncCreateUser(name,lastName,upload))
-      console.log(name,lastName,upload)
-  }
+  const handleUpdateUser = async() => 
+    dispatch(asyncCreateUser(name,lastName,upload))
+
+  
  
   return (
     <div className={classes.container} >

+ 5 - 5
src/components/AuthPage/index.tsx

@@ -6,8 +6,7 @@ import Authorization from './Authorization'
 import SMSCode from './SMSCode'
 import Registration from './Registration'
 import { authorizeUser } from '../../api-data'
-import {asyncLogin} from '../../redux/authorization/operations'
-
+import { asyncLogin } from '../../redux/authorization/operations'
 
 const AuthPage = () => {
   const [isQR, setIsQR] = useState<boolean>(false)
@@ -24,16 +23,17 @@ const AuthPage = () => {
     isCheckedLC && setIsChecked(isCheckedLC === 'true'?true:false)
   }, [])
 
+  const format = (a: string) => a.split(' ').join('').trim()
+
   const handleIsQR = (): void => setIsQR(!isQR)
 
   const handleSendCode = async (): Promise<void> => {
-      const res = await authorizeUser(number.split(' ').join('').trim(), country)
+      const res = await authorizeUser(format(number), country)
       res&&setIsCode(res)
   }
 
   const handleIsValidCode = async (e: React.ChangeEvent<HTMLInputElement>):Promise<void> => {
-    const value = e.target.value.trim().split(' ').join('');
-    if (isCode && value === isCode)
+    if (isCode && format(e.target.value) === isCode) 
       dispatch(await asyncLogin(number, isCode, () => setIsReg(!isReg)))
     }
   const handleIsCheck = (e: React.ChangeEvent<HTMLInputElement>): void => {

+ 9 - 9
src/components/DropZone/UploadAvatar/index.tsx

@@ -26,17 +26,22 @@ const useStyles = makeStyles({
 })
 
 interface IUploadAvatar {
-  setUpload: React.Dispatch<React.SetStateAction<object>>
+  setUpload: React.Dispatch<React.SetStateAction<any>>
 }
-function UploadAvatar({setUpload}:IUploadAvatar) {
+function UploadAvatar({ setUpload }: IUploadAvatar) {
+  
   const {
     acceptedFiles,
     getRootProps,
     getInputProps
   } = useDropzone({
-    accept: 'image/jpeg,image/png'
+    accept: 'image/jpeg,image/png',
   });
 
+    useEffect(() => {
+      setUpload(acceptedFiles[0])
+  }, [setUpload,acceptedFiles])
+
   const classes = useStyles()
   const acceptedFileItems = acceptedFiles.map((file: any) => (
     <ListItem key={file.path}>
@@ -49,16 +54,11 @@ function UploadAvatar({setUpload}:IUploadAvatar) {
    </ListItem>
   ));
 
-  useEffect(() => {
-    const file = acceptedFiles[0]
-    file&&setUpload(file)
-  }, [setUpload,acceptedFiles])
-
   return (
     <section className={classes.container} >
       <div {...getRootProps({ className: classes.dropZone })}>
         <InputLabel>Drag or drop avatar*</InputLabel>
-        <input {...getInputProps()} required/>
+        <input {...getInputProps()}/>
         <img
           alt='drop zone img'
           src='https://imagga.com/static/images/upload.svg'

+ 19 - 12
src/redux/authorization/operations/index.ts

@@ -9,29 +9,37 @@ import {
 
 import { setToken, loginUser,updateCredentials,updateUserAvatar } from '../../../api-data';
 
-const asyncCreateUser = (name:string, lastName: string,avatar:object) => async (dispatch:any) => {
+const asyncCreateUser = (name:string, lastName: string,file:any) => async (dispatch:any) => {
   try {
     dispatch(actionIsLoading(true));
-    await updateCredentials(name, lastName);
+    const reader: any = new FileReader()
+    const formData:any = new FormData()
+      reader.onload = async () => {
+        formData.append("avatar", file);
+        const data = await Promise.all([updateUserAvatar(formData), updateCredentials(name, lastName)])
+        const res = data.find(el => el.token)
+        res?.token&&dispatch(actionLogInSuccess(res.token))
+      }
+     await reader.readAsArrayBuffer(file)
   } catch (e) {
-    console.log(encodeURI)
+    console.log(e)
   } finally {
     dispatch(actionIsLoading(false));
   }
 };
 
 
+
 const asyncLogin = (number:string, code: string,cb:() => void ) => async (dispatch:any) => {
   try {
     dispatch(actionIsLoading(true));
-    const data = await loginUser<{token:string,registration: boolean}>(number, code);
-    if (!data?.token) throw new Error('bad request')
-    setToken.set(data.token)
-    if (data?.registration) {
-      cb()
-    } else {
-      dispatch(actionLogInSuccess(data.token))
-    }
+    const data = await loginUser<{ token: string, registered: boolean }>(number, code);
+    const token = data?.token
+    const registered = data?.registered
+    if (!token) return
+    setToken.set(token)
+    if (!registered) return cb()
+    dispatch(actionLogInSuccess(token))
   } catch (e) {
     dispatch(actionLogInReject());
     cb()
@@ -44,7 +52,6 @@ const asyncLogout = () => async (dispatch:any) => {
   try {
     dispatch(actionIsLoading(true));
     dispatch(actionLogOutSuccess());
-    localStorage.removeItem('isChecked')
     setToken.unset()
   } catch (e) {
     dispatch(actionLogOutReject());