I'm currently writing an App in React-Native, which also includes a login. I use AsyncStorage for saving the credentials. Now I want to show the user different Screens (Navigators) whether he is logged in or not. To check if he is logged in, I check if there are credentials in the AsyncStorage, and the function to check this returns a promise. So now when I call the function in my component, it wont wait until the promise has resolved and I don't have any idea on how to solve. I tried with but this also failed. Maybe you have any idea. Below my code. Thanks
import 'react-native-gesture-handler'
import { NavigationContainer } from '@react-navigation/native'
import AppNavigation from './navigation/AppNavigation.js'
import { ThemeProvider, Text } from 'react-native-magnus'
import { useState, useEffect, useCallback, Suspense} from 'react'
import {React } from 'react'
import getNutrientsCompare from './utils/getNutrientsCompare.js'
import getLoginSession from './utils/getLoginSession.js'
import Login from './pages/Login.js'
import { ActivityIndicator } from 'react-native'
const wait = (timeout) => {
return new Promise(resolve => setTimeout(resolve, timeout));
}
const RootElement = () => {
const [result, setResult] = useState(null)
getLoginSession().then(data => {
[loginSessionState, setLoginSessionState] = useState("");
if (loginSessionState != null) {
setResult((
<ThemeProvider>
<NavigationContainer >
<AppNavigation />
</NavigationContainer>
</ThemeProvider>))
} else {
setResult((
<ThemeProvider>
<Login>
</Login>
</ThemeProvider>
))
}
})
return result
}
const App = () => {
return (
<Suspense fallback={<ActivityIndicator />}>
<RootElement />
</Suspense>
)
}
export default App
CodePudding user response:
Give this a try
import { ActivityIndicator } from "react-native";
const RootElement = () => {
const [loggedIn, setLoggedIn] = useState(false);
const [loading, setLoading] = useState(true);
useEffect(() => {
(async () => {
try {
const data = await getLoginSession();
if (data != null) {
setLoggedIn(true);
}
} catch (error) {
setLoggedIn(false);
}
setLoading(false);
})();
}, []);
return (
<>
{!loading ? (
loggedIn ? (
<ThemeProvider>
<NavigationContainer>
<AppNavigation />
</NavigationContainer>
</ThemeProvider>
) : (
<ThemeProvider>
<Login />
</ThemeProvider>
)
) : (
<ActivityIndicator size="large" color="#00ff00" />
)}
</>
);
};