App.js 2.33 KB
import React, {useState} from 'react';
import {View} from 'react-native';
import {AppLoading} from 'expo';
import * as SecureStore from 'expo-secure-store';
import AsyncStorage from '@react-native-community/async-storage';
import axios from "axios";
import env from './env';
import {StatusBar} from 'expo-status-bar';
import {Provider} from 'react-redux';
import store from "./store";
import {AuthProvider} from "./AuthContext";
import RootNavigation from "./navigations/RootNavigation";

export default function App() {
    const [isAppLoading, setIsAppLoading] = useState(true);
    const [user, setUser] = useState(null);

    const loadAssets = async () => {
        return new Promise(async (resolve, reject) => {
            try {
                let cookie;
                if (SecureStore.isAvailableAsync()) {
                    cookie = await SecureStore.getItemAsync('cookie');
                } else {
                    cookie = await AsyncStorage.getItem('cookie');
                }
                if (cookie) {
                    axios.defaults.headers.Cookie = cookie;
                    const res = await axios.get(`${env.HTTP_OR_HTTPS}://${env.HOST}:${env.PORT}/user/loadMe`, {
                        withCredentials: true
                    });
                    const {user} = res.data;
                    setUser(user);
                }
                return resolve();
            } catch (e) {
                console.error(e);
                return reject();
            }
        })
    };
    const onFinish = async () => {
        setIsAppLoading(false);
    };
    const onError = (err) => {
        console.error(err);
    };

    return (
        <>
            {isAppLoading
                ?
                <AppLoading
                    startAsync={loadAssets}
                    onFinish={onFinish}
                    onError={onError}/>
                :
                <View style={{
                    flex: 1,
                    flexDirection: 'column',
                    justifyContent: 'center'
                }}>
                    <Provider store={store}>
                        <AuthProvider user={user}>
                            <RootNavigation/>
                        </AuthProvider>
                    </Provider>
                    <StatusBar/>
                </View>
            }
        </>
    );
}