aboutsummaryrefslogtreecommitdiffstats
path: root/App.js
blob: c74c19cb57123a8ae2cbf7e38f84659eafdd9b87 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
import { StatusBar } from 'expo-status-bar';
import { StyleSheet, SafeAreaView, Text } from 'react-native';
import { useState, useEffect } from 'react';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { Login, List, Edit } from './components'

export default function App() {
  const [session, setSession] = useState();
  const [error, setError] = useState(null);
  const [edit, setEdit] = useState(null)

  const login = async (e, p) => {
    try {
      const response = await fetch('https://apps.pruss.it/api/login', {
        method: 'POST',
        headers: { 'Content-Type': 'plain/text; charset=utf-8' },
        body: JSON.stringify({ email: e, password: p })
      })
      const cookies = response.headers?.map?.['set-cookie']
      const data = await response.json()
      if (data?.isLoggedIn) {
        await AsyncStorage.setItem('session', JSON.stringify({...data, cookies}))
        setSession({ ...data, cookies })
      }
    } catch(e) {
      showError('Error while logging in')
    }
  }

  const showError = (e) => {
    setError(e)
    setTimeout(() => { setError(null) }, 2000)
  }

  useEffect(() => {
    AsyncStorage.getItem('session')
      .then(s => setSession(JSON.parse(s)))
      .catch(() => setSession(null))
  }, []);

  if (error) return (
    <SafeAreaView style={styles.container}>
      <Text style={styles.error}>{error}</Text>
    </SafeAreaView>
  )

  if (session === undefined) return (
    <SafeAreaView style={styles.container}>
      <Text>Loading...</Text>
    </SafeAreaView>
  );

  return (
    <SafeAreaView style={styles.container}>
      {
        session === null
          ? <Login login={login} />
          : edit
            ? (
              <Edit
                edit={edit}
                setEdit={setEdit}
                session={session}
                setSession={setSession}
                showError={showError}
              />
            ) : (
              <List
                session={session}
                showError={showError}
                setEdit={setEdit}
              />
            )
      }
      <StatusBar style="auto" />
    </SafeAreaView>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#000',
    // height: '100%',
  },
  error: {
    color: 'red',
  }
});