Fakultas Ilmu Komputer UI

index.tsx 2.37 KB
Newer Older
1
2
import React, { FC, useContext, useState } from 'react';
import { StyleSheet, Text, View } from 'react-native';
3
import { UserContext } from 'provider';
4
import { useAuthEffect, useForm } from 'hooks';
5
6

import { GoogleLoginButton } from '../components';
7
import { BigButton, Toast, Loader } from 'components/core';
8
9
10

import { fieldValidation, initialValues, textField } from './schema';
import { generateValidationSchema } from 'utils/form';
11
import { layoutStyles } from 'styles';
12
13
14
15
import { TextField } from 'components/form';
import { Section } from 'components/layout';

const isPasswordField = (name: string) => name === 'password';
16
17

const Login: FC = () => {
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
  const { login, isLoading, loginWithGoogle } = useContext(UserContext);
  const [nonFieldError, setNonFieldError] = useState<string | null>();

  const {
    getTextInputProps,
    handleSubmit,
    isSubmitting,
    setFieldError,
  } = useForm({
    initialValues,
    validationSchema: generateValidationSchema(fieldValidation),
    onSubmit: async (values) => {
      const response = await login(values);

      if (!response.success) {
        const error = response.error;

        setFieldError('email', error.email);
        setFieldError('password', error.password);
        setNonFieldError(error.non_field_errors);

        Toast.show({
          type: 'error',
          text1: 'Gagal login akun',
          text2: 'Terjadi kesalahan login. Silakan coba lagi',
        });
      }
    },
  });
47

Wulan Mantiri's avatar
Wulan Mantiri committed
48
  const isProcessing = useAuthEffect();
49

50
51
52
  if (isProcessing) {
    return <Loader />;
  }
53
54
  return (
    <View style={layoutStyles}>
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
      {textField.map(({ name, label, required, placeholder }, i) => (
        <TextField
          key={`field${i}`}
          label={label}
          required={required}
          placeholder={placeholder}
          {...getTextInputProps(name)}
          secureTextEntry={isPasswordField(name)}
        />
      ))}
      {nonFieldError && (
        <Text style={styles.nonfieldError}>{nonFieldError}</Text>
      )}
      <Section>
        <BigButton
          title="login"
          onPress={handleSubmit}
          loading={isSubmitting}
          testID="loginButton"
        />
      </Section>
      <Section>
        <GoogleLoginButton onPress={loginWithGoogle} isLoading={isLoading} />
      </Section>
79
80
81
82
    </View>
  );
};

83
84
85
86
const styles = StyleSheet.create({
  nonfieldError: { color: 'red' },
});

87
export default Login;