import 'react-native-gesture-handler'; import React, { useEffect, useState } from 'react'; import { createStackNavigator } from '@react-navigation/stack'; import { DefaultTheme } from 'react-native-paper' import Intro from '../screens/Intro'; import { RegistrationFormProvider } from '../contexts/RegisterContext'; import { MapProvider } from '../contexts/MapContext'; import TabsNavigator from './TabsNavigator'; import { useAuthState } from '../contexts/AuthContext'; import RegisterMain from '../screens/RegisterMain'; import Splash from '../screens/Splash'; import * as SecureStore from 'expo-secure-store'; import axios from 'axios'; const MainStack = createStackNavigator(); const theme = { ...DefaultTheme, colors: { primary: '#df3f3f', accent: 'white', }, } const MainStackNavigator = () => { const {authDispatch, authState} = useAuthState(); useEffect(() => { const checkToken = async () => { let accessToken; try { accessToken = await SecureStore.getItemAsync('accessToken'); if (accessToken) { try { // send a test request to check if access token valid const response = await axios.get(`http://10.0.0.151:8000/api/me/`, { headers: { 'Authorization': "Bearer " + accessToken } }); if (response.status === 200) { // response token is valid, set it in state so user is directed to the map authDispatch({type: "SET_ACCESS_TOKEN", payload: accessToken}); } } catch (error) { // initial access token is invalid, user has to login accessToken = await SecureStore.deleteItemAsync('accessToken'); authDispatch({type: "SET_ACCESS_TOKEN", payload: null}); // other errors funnel here so log them console.log(error); console.log(error.response.data); } } else { // access token doesnt exist, user will be directed to the intro screen authDispatch({type: "SET_ACCESS_TOKEN", payload: null}); } } catch (err) { console.log(err); } } checkToken(); }, [authState.accessToken]) return( {authState.isStarting ? : <> {authState.accessToken ? : <> } } ) } export default MainStackNavigator;