Browse Source

fix: reworked api calls | reworked screens | new api call

Oleksandr Honcharov 1 year ago
parent
commit
c03f92e8b0

+ 8 - 2
src/modules/auth/api/auth-api.tsx → src/modules/auth/api/auth-api.ts

@@ -1,18 +1,22 @@
 import { request } from '../../../utils';
 import { API } from '../../../types';
 import { ResponseType } from '../response-type';
+
 import { UserRegistrationData } from './queries/use-post-register';
+import { UserResetPasswordData } from './queries/use-post-reset-password';
 
 export interface PostLoginUserReturn extends ResponseType {
   token: string;
 }
 
 export interface PostRegisterUserReturn extends ResponseType {
-  token: string;
+  token: string; // TODO: optional
   uid: string;
   mail: 1 | 0;
 }
 
+export interface UserResetPasswordReturn extends ResponseType {}
+
 export const authApi = {
   loginUser: (data: { login: string; pass: string }) =>
     request.postForm<PostLoginUserReturn>(API.LOGIN, data),
@@ -27,5 +31,7 @@ export const authApi = {
     } as unknown as Blob);
 
     return request.postForm<PostRegisterUserReturn>(API.REGISTER, formData);
-  }
+  },
+  resetPassword: (data: UserResetPasswordData) =>
+    request.postForm<UserResetPasswordReturn>(API.RESET_PASSWORD, data)
 };

+ 2 - 1
src/modules/auth/api/auth-query-keys.tsx

@@ -1,4 +1,5 @@
 export const authQueryKeys = {
   loginUser: () => ['loginUser'] as const,
-  registerUser: () => ['registerUser'] as const
+  registerUser: () => ['registerUser'] as const,
+  resetPassword: () => ['resetPassword'] as const
 };

+ 11 - 7
src/modules/auth/api/queries/use-post-login.tsx

@@ -1,15 +1,19 @@
-import { useQuery } from '@tanstack/react-query';
+import { useMutation } from '@tanstack/react-query';
 import { authApi, PostLoginUserReturn } from '../auth-api';
 import { BaseAxiosError } from '../../../../types';
 import { authQueryKeys } from '../auth-query-keys';
 
-export const usePostLogin = (data: { login: string; pass: string }, enabled: boolean) => {
-  return useQuery<PostLoginUserReturn, BaseAxiosError>({
-    queryKey: authQueryKeys.loginUser(),
-    queryFn: async () => {
+type LoginTypes = {
+  login: string;
+  pass: string;
+};
+
+export const useLoginMutation = () => {
+  return useMutation<PostLoginUserReturn, BaseAxiosError, LoginTypes, PostLoginUserReturn>({
+    mutationKey: authQueryKeys.loginUser(),
+    mutationFn: async (data) => {
       const response = await authApi.loginUser(data);
       return response.data;
-    },
-    enabled
+    }
   });
 };

+ 13 - 9
src/modules/auth/api/queries/use-post-register.tsx

@@ -1,5 +1,5 @@
-import { useQuery } from '@tanstack/react-query';
-import { authApi, PostLoginUserReturn } from '../auth-api';
+import { useMutation } from '@tanstack/react-query';
+import { authApi, PostRegisterUserReturn } from '../auth-api';
 import { BaseAxiosError } from '../../../../types';
 import { authQueryKeys } from '../auth-query-keys';
 
@@ -10,7 +10,7 @@ export type UserRegistrationData = {
     password: string;
     first_name: string;
     last_name: string;
-    date_of_birth: Date;
+    date_of_birth: string;
     homebase: number;
   };
   photo: {
@@ -20,13 +20,17 @@ export type UserRegistrationData = {
   };
 };
 
-export const usePostRegister = (data: UserRegistrationData, enabled: boolean) => {
-  return useQuery<PostLoginUserReturn, BaseAxiosError>({
-    queryKey: authQueryKeys.registerUser(),
-    queryFn: async () => {
+export const useRegisterMutation = () => {
+  return useMutation<
+    PostRegisterUserReturn,
+    BaseAxiosError,
+    UserRegistrationData,
+    PostRegisterUserReturn
+  >({
+    mutationKey: authQueryKeys.registerUser(),
+    mutationFn: async (data) => {
       const response = await authApi.registerUser(data);
       return response.data;
-    },
-    enabled
+    }
   });
 };

+ 23 - 0
src/modules/auth/api/queries/use-post-reset-password.tsx

@@ -0,0 +1,23 @@
+import { useMutation } from '@tanstack/react-query';
+import { authApi, UserResetPasswordReturn } from '../auth-api';
+import { BaseAxiosError } from '../../../../types';
+import { authQueryKeys } from '../auth-query-keys';
+
+export type UserResetPasswordData = {
+  email: string;
+};
+
+export const useResetPasswordMutation = () => {
+  return useMutation<
+    UserResetPasswordReturn,
+    BaseAxiosError,
+    UserResetPasswordData,
+    UserResetPasswordReturn
+  >({
+    mutationKey: authQueryKeys.resetPassword(),
+    mutationFn: async (data) => {
+      const response = await authApi.resetPassword(data);
+      return response.data;
+    }
+  });
+};

+ 20 - 14
src/screens/LoginScreen/index.tsx

@@ -1,6 +1,6 @@
-import { FC, useState } from 'react';
+import { FC } from 'react';
 import { View } from 'react-native';
-import { NavigationProp } from '@react-navigation/native';
+import { NavigationProp, useNavigation, CommonActions } from '@react-navigation/native';
 import { Formik } from 'formik';
 import * as yup from 'yup';
 
@@ -10,7 +10,7 @@ import { ButtonVariants } from '../../types/components';
 import { storageSet } from '../../storage';
 import { NAVIGATION_PAGES } from '../../types';
 
-import { usePostLogin } from '../../modules/auth/api/queries/use-post-login';
+import { useLoginMutation } from '../../modules/auth/api/queries/use-post-login';
 
 type Props = {
   navigation: NavigationProp<any>;
@@ -22,15 +22,19 @@ const LoginSchema = yup.object({
 });
 
 const LoginScreen: FC<Props> = ({ navigation }) => {
-  const [login, setLogin] = useState('');
-  const [pass, setPass] = useState('');
+  const { dispatch, navigate } = useNavigation();
 
-  const { data, refetch } = usePostLogin({ login, pass }, false);
+  const { data, mutate: userLogin } = useLoginMutation();
 
   if (data) {
     if (data.token) {
       storageSet('token', data.token);
-      // TODO: navigate to app
+      dispatch(
+        CommonActions.reset({
+          index: 1,
+          routes: [{ name: NAVIGATION_PAGES.IN_APP }]
+        })
+      );
     }
   }
 
@@ -42,11 +46,11 @@ const LoginScreen: FC<Props> = ({ navigation }) => {
           login: '',
           pass: ''
         }}
-        onSubmit={(values) => {
-          setLogin(values.login);
-          setPass(values.pass);
-
-          refetch();
+        onSubmit={({ login, pass }) => {
+          userLogin({
+            login,
+            pass
+          });
         }}
         validationSchema={LoginSchema}
       >
@@ -61,7 +65,9 @@ const LoginScreen: FC<Props> = ({ navigation }) => {
                 onChange={props.handleChange('login')}
                 value={props.values.login}
                 onBlur={props.handleBlur('login')}
-                formikError={props.touched.login && props.errors.login}
+                formikError={
+                  data?.result_description || (props.touched.login && props.errors.login)
+                }
               />
               <Input
                 header={'Password'}
@@ -70,7 +76,7 @@ const LoginScreen: FC<Props> = ({ navigation }) => {
                 onChange={props.handleChange('pass')}
                 value={props.values.pass}
                 onBlur={props.handleBlur('pass')}
-                formikError={props.touched.pass && props.errors.pass}
+                formikError={data?.result_description || (props.touched.pass && props.errors.pass)}
               />
             </View>
             <View style={{ gap: 30, marginTop: '5%' }}>

+ 14 - 34
src/screens/RegisterScreen/EditAccount/index.tsx

@@ -1,4 +1,4 @@
-import React, { useState } from 'react';
+import React from 'react';
 import { View, ScrollView } from 'react-native';
 import { Formik } from 'formik';
 import * as yup from 'yup';
@@ -6,48 +6,30 @@ import * as yup from 'yup';
 import { AvatarPicker, BigText, Button, Header, Input, PageWrapper } from '../../../components';
 import { InputDatePicker } from '../../../components/Calendar/InputDatePicker';
 import { ModalFlatList } from '../../../components/FlatList/modal-flatlist';
+import { useRegisterMutation } from '../../../modules/auth/api/queries/use-post-register';
+import { storageSet } from '../../../storage';
+
 import store from '../../../storage/zustand';
-import {
-  usePostRegister,
-  UserRegistrationData
-} from '../../../modules/auth/api/queries/use-post-register';
 
 const SignUpSchema = yup.object({
   first_name: yup.string().required(),
   last_name: yup.string().required(),
-  date_of_birth: yup.date().required(),
+  date_of_birth: yup.string().required(),
   homebase: yup.number().required()
 });
 
 //TODO: formik avatar | date and flatlist error shown
 
 const EditAccount = () => {
-  const [requestData, setRequestData] = useState<UserRegistrationData>({
-    user: {
-      username: '',
-      last_name: '',
-      first_name: '',
-      homebase: 1,
-      date_of_birth: new Date(),
-      email: '',
-      password: ''
-    },
-    photo: {
-      type: '',
-      name: '',
-      uri: ''
-    }
-  });
-
   const [user] = store((state) => [state.registration.user]);
 
-  const { data, error, refetch } = usePostRegister(
-    {
-      user: requestData.user,
-      photo: requestData.photo
-    },
-    false
-  );
+  const { data, error, mutate: userRegister } = useRegisterMutation();
+
+  if (data) {
+    if (data.token) {
+      storageSet('token', data.token);
+    }
+  }
 
   return (
     <PageWrapper>
@@ -64,7 +46,7 @@ const EditAccount = () => {
               },
               first_name: '',
               last_name: '',
-              date_of_birth: new Date(),
+              date_of_birth: '',
               homebase: 0
             }}
             validationSchema={SignUpSchema}
@@ -84,9 +66,7 @@ const EditAccount = () => {
                 }
               };
 
-              setRequestData(data);
-
-              refetch();
+              userRegister(data);
             }}
           >
             {(props) => (

+ 46 - 27
src/screens/ResetPasswordScreen/index.tsx

@@ -1,41 +1,60 @@
-import React, { FC, useState } from 'react';
+import React, { FC } from 'react';
 import { Text, View } from 'react-native';
-import type { NavigationProp } from '@react-navigation/native';
+import { Formik } from 'formik';
+import * as yup from 'yup';
 
 import { PageWrapper, Header, BigText, Button, Input } from '../../components/';
-import { NAVIGATION_PAGES } from '../../types';
 
 import { styles } from './styles';
+import { useResetPasswordMutation } from '../../modules/auth/api/queries/use-post-reset-password';
 
-type Props = {
-  navigation: NavigationProp<any>;
-};
-
-const ResetPasswordScreen: FC<Props> = ({ navigation }) => {
-  const [email, setEmail] = useState('');
+const ResetPasswordSchema = yup.object({
+  email: yup.string().email().required()
+});
 
-  //TODO: Add pass checks | add res pass functionality
+const ResetPasswordScreen: FC = () => {
+  const { data, error, mutate: resetPassword } = useResetPasswordMutation();
 
   return (
     <PageWrapper>
       <Header label={'Reset Password'} />
-      <View style={{ gap: 15 }}>
-        <BigText>Please enter your valid email</BigText>
-        <Text style={styles.smallText}>
-          Type email which you used for registration and check your inbox for further instructions
-        </Text>
-        <Input
-          onChange={(s) => setEmail(s)}
-          placeholder={'Email'}
-          header={'Email address'}
-          inputMode={'email'}
-        />
-      </View>
-      <View style={{ marginTop: '10%' }}>
-        <Button onPress={() => navigation.navigate(NAVIGATION_PAGES.RESET_PASSWORD_DEEP)}>
-          Send
-        </Button>
-      </View>
+      <Formik
+        initialValues={{
+          email: ''
+        }}
+        onSubmit={({ email }) => {
+          resetPassword({
+            email
+          });
+        }}
+        validationSchema={ResetPasswordSchema}
+      >
+        {(props) => (
+          <>
+            <View style={{ gap: 15 }}>
+              <BigText>Please enter your valid email</BigText>
+              <Text style={styles.smallText}>
+                Type email which you used for registration and check your inbox for further
+                instructions
+              </Text>
+              <Input
+                header={'Email address'}
+                placeholder={'Email'}
+                inputMode={'email'}
+                onChange={props.handleChange('email')}
+                value={props.values.email}
+                onBlur={props.handleBlur('email')}
+                formikError={
+                  data?.result_description || (props.touched.email && props.errors.email)
+                }
+              />
+            </View>
+            <View style={{ marginTop: '10%' }}>
+              <Button onPress={props.handleSubmit}>Send</Button>
+            </View>
+          </>
+        )}
+      </Formik>
     </PageWrapper>
   );
 };

+ 2 - 0
src/types/api.ts

@@ -8,12 +8,14 @@ export enum API_ROUTE {
 export enum API_ENDPOINT {
   LOGIN = 'login',
   REGISTER = 'join',
+  RESET_PASSWORD = 'recover-password',
   GET_REGIONS = 'get-regions'
 }
 
 export enum API {
   LOGIN = `${API_ROUTE.USER}/${API_ENDPOINT.LOGIN}`,
   REGISTER = `${API_ROUTE.USER}/${API_ENDPOINT.REGISTER}`,
+  RESET_PASSWORD = `${API_ROUTE.USER}/${API_ENDPOINT.RESET_PASSWORD}`,
   GET_REGIONS = `${API_ROUTE.REGIONS}/${API_ENDPOINT.GET_REGIONS}`
 }