LoginComponent.tsx 4.54 KB
Newer Older
1
import React, { useEffect, useState } from 'react';
2
import { FormProvider, SubmitHandler, useForm } from 'react-hook-form';
3
import {
4
5
  ActivityIndicator,
  Button,
6
  Image,
7
  Pressable,
8
  StyleSheet,
9
  Text,
10
  useWindowDimensions,
11
  View,
12
} from 'react-native';
13
import AwesomeAlert from 'react-native-awesome-alerts';
14
15
16
17
18
import { useDispatch, useSelector } from 'react-redux';
import Logo from '../assets/images/cinema.png';
import { signIn, signUp } from '../store/ducks/auth/actions';
import { ApplicationState } from '../store/interface';
import CustomInput from './common/CustomInput';
Peter Skaar Nordby's avatar
Peter Skaar Nordby committed
19
20

export default function App() {
21
  const { height } = useWindowDimensions();
Mithunan Sivakumar's avatar
Mithunan Sivakumar committed
22
23
24

  const methods = useForm<FormValues>({
    defaultValues: {
25
26
      email: '',
      password: '',
Mithunan Sivakumar's avatar
Mithunan Sivakumar committed
27
    },
28
29
30
    mode: 'onSubmit',
    reValidateMode: 'onBlur',
  });
Mithunan Sivakumar's avatar
Mithunan Sivakumar committed
31

32
33
34
35
  const {
    formState: { errors },
    handleSubmit,
  } = methods;
Mithunan Sivakumar's avatar
Mithunan Sivakumar committed
36

37
  // Handle form submit
38
  const onSubmit: SubmitHandler<FormValues> = (values: FormValues) => onFinish(values);
Mithunan Sivakumar's avatar
Mithunan Sivakumar committed
39
40
41
42
43
44
45
  interface FormValues {
    email: string;
    password: string;
    username?: string;
  }

  const [isLogin, setIsLogin] = useState(true);
46
  const dispatch = useDispatch();
47
  const { loading, error } = useSelector(({ auth }: ApplicationState) => auth);
48
  const [alertMessage, setAlertmessage] = useState('');
49

50
51
  // Form completed
  const onFinish = (values: FormValues) => {
Mithunan Sivakumar's avatar
Mithunan Sivakumar committed
52
    if (isLogin) {
53
      // If the form is in loginMode, dispatch the signIn action
54
      dispatch(signIn({ email: values.email, password: values.password }));
Mithunan Sivakumar's avatar
Mithunan Sivakumar committed
55
    } else {
56
      // If the form is in signUpMode, dispatch the signUp action
57
58
59
60
61
      dispatch(
        signUp({
          email: values.email,
          username: values.username || '',
          password: values.password,
62
        }),
63
      );
Mithunan Sivakumar's avatar
Mithunan Sivakumar committed
64
    }
65
  };
Mithunan Sivakumar's avatar
Mithunan Sivakumar committed
66
67

  useEffect(() => {
68
    // If there is an error, show the alert
Mithunan Sivakumar's avatar
Mithunan Sivakumar committed
69
    if (error) {
70
71
      setAlertmessage(error);
    } else {
72
      // If the error state updated and no error was found, clear the alert
73
      setAlertmessage('');
Mithunan Sivakumar's avatar
Mithunan Sivakumar committed
74
75
76
77
    }
  }, [error]);

  const styles = StyleSheet.create({
78
79
80
81
82
83
    alert: {
      width: 400,
    },
    alertTitle: {
      color: 'red',
    },
Mithunan Sivakumar's avatar
Mithunan Sivakumar committed
84
    root: {
85
86
87
88
      flex: 1,
      justifyContent: 'center',
      width: '70%',
      height: '100%',
Mithunan Sivakumar's avatar
Mithunan Sivakumar committed
89
90
    },
    logo: {
91
      minWidth: 200,
Mithunan Sivakumar's avatar
Mithunan Sivakumar committed
92
93
94
95
      maxWidth: 300,
      maxHeight: 200,
    },
    container: {
96
      width: '100%',
Mithunan Sivakumar's avatar
Mithunan Sivakumar committed
97
98
      padding: 15,
      marginVertical: 5,
99
      alignItems: 'center',
Mithunan Sivakumar's avatar
Mithunan Sivakumar committed
100
101
102
103
      borderRadius: 5,
    },
    subText: {
      color: '#2e78b7',
Mithunan Sivakumar's avatar
Mithunan Sivakumar committed
104
105
106
    },
    button: {
      marginTop: 10,
107
108
    },
  });
Peter Skaar Nordby's avatar
Peter Skaar Nordby committed
109
110

  return (
111
    <View style={styles.root}>
112
      <Image source={Logo} style={[styles.logo, { height: height * 0.3 }]} resizeMode='contain' />
113
      <FormProvider {...methods}>
114
        {isLogin ? null : (
115
          <CustomInput
116
117
            required={isLogin ? false : true}
            error={errors.username ? true : false}
118
119
120
            errorMessage='Du må fylle inn brukernavn'
            name='username'
            placeholder='username'
121
          />
122
123
124
125
        )}
        <CustomInput
          required={true}
          error={errors.email ? true : false}
126
127
128
          errorMessage='Du må fylle inn e-post'
          name='email'
          placeholder='email'
129
130
131
132
        />
        <CustomInput
          required={true}
          error={errors.password ? true : false}
133
134
          errorMessage='Passorder må oppfylle krav ...'
          name='password'
135
          secureTextEntry={true}
136
          placeholder='password'
137
138
139
140
141
142
        />
        <View style={styles.button}>
          <Button
            disabled={loading}
            onPress={handleSubmit(onSubmit)}
            title={isLogin ? 'Login' : 'Register'}
143
          />
144
145
146
147
148
149
150
151
          <Pressable
            onPress={() => {
              setIsLogin(!isLogin);
              methods.clearErrors();
            }}
            style={styles.container}
          >
            <Text style={styles.subText}>
152
              {!isLogin ? 'Already have a user? Login.' : 'Need a new user? Register.'}
153
154
155
            </Text>
          </Pressable>
        </View>
156
      </FormProvider>
157
158
159
160
161
162
163
164
      <AwesomeAlert
        contentContainerStyle={styles.alert}
        titleStyle={styles.alertTitle}
        show={alertMessage.length > 0}
        title={`${isLogin ? 'Login' : 'Registration'} failed`}
        message={`Server responded with: ${alertMessage}`}
        closeOnTouchOutside={true}
        showConfirmButton={true}
165
        confirmText='Ok'
166
167
168
169
        onConfirmPressed={() => {
          setAlertmessage('');
        }}
      />
170
      {loading && <ActivityIndicator size='large' color='#00ff00' />}
Mithunan Sivakumar's avatar
Mithunan Sivakumar committed
171
    </View>
Peter Skaar Nordby's avatar
Peter Skaar Nordby committed
172
  );
173
}