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

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

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

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

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

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

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

66
  // TODO If the redux state contains an error, display an error alert
Mithunan Sivakumar's avatar
Mithunan Sivakumar committed
67
68
  useEffect(() => {
    if (error) {
69
70
71
      setAlertmessage(error);
    } else {
      setAlertmessage('');
Mithunan Sivakumar's avatar
Mithunan Sivakumar committed
72
73
74
75
    }
  }, [error]);

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

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