سلام استاد
در مورد جلسه 84 stack action . دستور مربوط به اینکه صفحه home برود را با دستور جدید نوشتم . همچنین خروج با دو بار ضربه را هم اضافه کردم . برنامه به درستی کار می کند . اما اگر برنامه را کلا از حافظه clear پاک کنم منتظر پنجره wellcome هستم ولی جلو نمی رود و بروی لود اولیه متوقف هست تست کردم اگرtoken , userId را بطور دستی حذف کنم برنامه کار می کند مجور شدم دستور
حذف توکن و userId تو برنامه همیشه اینجوری بزارم . که این خیلی افتضاح هستش . کار اصلی که می خواستیم اگر یه بار login کرد دوباره پنجره login نیاد حتی با reload کردن برنامه از دست رفته .
const checkForNet =async()=>{
await AsyncStorage.removeItem("token");
await AsyncStorage.removeItem("userId");
const state=await netinfo.fetch();
console.log('connection type is ',state.type);
console.log("is connected:",state.isConnected);
if(!state.isConnected) confirmationAlet();
else {
const token = await AsyncStorage.getItem("token");
const userId = JSON.parse(await AsyncStorage.getItem("userId"));
if (token !== null && userId !== null) {
const decodedToken = decodeToken(token);
console.log(decodedToken);
console.log(userId);
if (decodedToken.user.userId === userId)
//navigation.navigate("Home");
{ navigation.dispatch(StackActions.replace("Home"));
navigation.navigate("Home");}
else {
await AsyncStorage.removeItem("token");
await AsyncStorage.removeItem("userId");
navigation.navigate("Login");
}
}
}
}import { StyleSheet, View,ImageBackground,Image,Alert,BackHandler } from 'react-native'
import netinfo from '@react-native-community/netinfo'
import React , {useCallback, useEffect,useState}from 'react'
import CustomButton from '../components/shared/CustomButton';
import * as SplashScreen from 'expo-splash-screen';
import getFont from '../utils/font';
import ToplearnText from './../components/shared/ToplearnText';
import { useDimensions,useDeviceOrientation } from '@react-native-community/hooks';
import { decodeToken } from '../api/token';
import AsyncStorage from '@react-native-async-storage/async-storage';
import {StackActions,useNavigationState} from '@react-navigation/native'
import { costomToast } from './../utils/toasts';
const WellComescreen = ({ navigation }) => {
const [appIsReady, setAppIsReady] = useState(false);
const {screen,window}=useDimensions();
const {landscape,portrait}=useDeviceOrientation();
const confirmationAlet=()=>{
return Alert.alert(
"بررسی ارتباط با سرور...",
"جهت استفاده از برنامه باید به اینترنت متصل باشید",
[{text:"باشه" ,onPress:BackHandler.exitApp,}],
{cancelable:false}
);
}
const screenIndex = useNavigationState((state) => state.index);
useEffect(() => {
let currentCount = 0;
console.log(screenIndex);
if (screenIndex <= 0) {
BackHandler.addEventListener("hardwareBackPress", () => {
if (currentCount === 1) {
BackHandler.exitApp();
return true;
}
currentCount += 1;
costomToast("برای خروج دوباره دکمه برگشت را لمس بنمایید");
setTimeout(() => {
currentCount = 0;
}, 1000);
return true;
});
}
}, []);
useEffect(() => {
const checkForNet =async()=>{
await AsyncStorage.removeItem("token");
await AsyncStorage.removeItem("userId");
const state=await netinfo.fetch();
console.log('connection type is ',state.type);
console.log("is connected:",state.isConnected);
if(!state.isConnected) confirmationAlet();
else {
const token = await AsyncStorage.getItem("token");
const userId = JSON.parse(await AsyncStorage.getItem("userId"));
if (token !== null && userId !== null) {
const decodedToken = decodeToken(token);
console.log(decodedToken);
console.log(userId);
if (decodedToken.user.userId === userId)
//navigation.navigate("Home");
navigation.dispatch(StackActions.replace("Home"));
else {
await AsyncStorage.removeItem("token");
await AsyncStorage.removeItem("userId");
navigation.navigate("Login");
}
}
}
}
/////////////////////////////
async function prepare() {
try {
// Keep the splash screen visible while we fetch resources
await SplashScreen.preventAutoHideAsync();
// Pre-load fonts, make any API calls you need to do here
await getFont();
// await Font.loadAsync(Entypo.font);
// Artificially delay for two seconds to simulate a slow loading
// experience. Please remove this if you copy and paste the code!
//await new Promise(resolve => setTimeout(resolve, 2000));
} catch (e) {
console.warn(e);
} finally {
// Tell the application to render
setAppIsReady(true);
}
}
checkForNet();
prepare();
}, []);
const onLayoutRootView = useCallback(async () => {
if (appIsReady) {
// This tells the splash screen to hide immediately! If we call this after
// `setAppIsReady`, then we may see a blank screen while the app is
// loading its initial state and rendering its first pixels. So instead,
// we hide the splash screen once we know the root view has already
// performed layout.
await SplashScreen.hideAsync();
console.log(screen.height)
}
}, [appIsReady]);
if (!appIsReady) {
return null;
}
////// old code
return (
<ImageBackground blurRadius={10} onLayout={onLayoutRootView}
source={require("../assets/bg1.jpg")}
style={styles.backGroundImage}>
<View style={styles.logocontainer}>
<Image source={require('../assets/logo.png')}
style={styles.logo}/>
<ToplearnText
size="3"
fontFamily="yekan"
styles={styles.logoText}>
خودآموزی ، کسب تجربه ، ورود به بازار کار
</ToplearnText>
<View style={[styles.btncontainer,{ marginTop:screen.height-460}]}>
<CustomButton title="ورود به سیستم"
onPress={() => navigation.navigate("Login")}
color="royalblue" />
<CustomButton title="ثبت نام"
onPress={()=>navigation.navigate('Register')}
color="tomato" />
</View>
</View>
</ImageBackground>
)
}
export default WellComescreen
const styles = StyleSheet.create({
backGroundImage:{
flex: 1,
alignItems: 'center',
justifyContent: 'flex-start',
},
logcontainer:{
alignItems: 'center',
justifyContent:"center",
},
logo:{
width:150,
height:150,
marginTop:30,
marginHorizontal:160,
alignItems:"center",
justifyContent:"center"
},
logoText:{
fontWeight:"bold",
alignItems:"center",
justifyContent:"center",
marginHorizontal:35,
marginTop:12,
color:"tomato",
},
btncontainer:{
//marginTop:250,
marginHorizontal:40,
}
}) import { StyleSheet, View,Image } from 'react-native'
import React,{useEffect} from 'react'
import * as Yup from 'yup';
import { ToplearnForm,SubmitButton,ToplearnFormField} from '../components/forms'
import Screen from '../components/shared/Screen';
import { loadingToast, succesToast,costomToast } from '../utils/toasts';
import { loginUser } from '../api/users';
import Toast from 'react-native-tiny-toast';
const validationScema=Yup.object().shape({
email:Yup.string().required("این فیلد الزامی می باشد")
.email("ایمیل وارد شده معتبر نمی باشد"),
password:Yup.string().required('کلمه عبور وارد نشده است')
.min(4,'حدافل باید 4 کارکتر باشد'),
})
const LoginScreen = ({ navigation,route }) => {
useEffect(() => {
if (route.params.successRegister)
succesToast("ثبت نام موفقیت آمیز بود");
}, []);
const handleUserLogin = async (user) => {
try {
loadingToast("درحال ارتباط با سرور...");
const status= await loginUser(user);
if (status==200){
Toast.hide();
succesToast("ورود موفقیت آمیز بود");
//navigation.navigate("Home");
navigation.reset({
index: 0,
routes: [{ name: "Home" }],
});
}
else {
Toast.hide();
costomToast("ایمیل کاربری یا رمز عبور صحیح نمی باشد!");
}
} catch (err) {
Toast.hide();
console.log(err);
}
};
return (
<Screen style={styles.loginContainer}>
<Image style={styles.logoStyle} source={require('../assets/logo.png')} />
<ToplearnForm
initialValues={{email:"",password:""}}
//onSubmit={() =>navigation.navigate("Home")}
onSubmit={(user) => {
handleUserLogin(user);
}}
validationSchema={validationScema}
>
<ToplearnFormField icon='email'
placeholder='ایمیل کاربر'
autoCompleteType="email"
keyboardType='email-address'
placeholderTextColor='royalblue'
autoCorrect={false}
name="email"
/>
<ToplearnFormField icon='onepassword'
placeholder='کلمه عبور'
autoCorrect={false}
secureTextEntry={true}
placeholderTextColor='royalblue'
name="password"
/>
<View styel={{width:"80%",marginTop:"40"}}>
<SubmitButton title="ورود کاربر" color="tomato"/>
</View>
</ToplearnForm>
</Screen>
)
}
export default LoginScreen
const styles = StyleSheet.create({
loginContainer:{
alignItems: "center",
},
logoStyle:{
width:150,
height:150,
marginTop:30,
marginHorizontal:160,
alignItems:"center",
justifyContent:"center",
marginBottom:100,
},
AppButtom:{
marginTop:80,
}
})سلام دوست من
می تونی چک کنی که اگر token و ... موجود بود ازش استفاده کنه و پیش بره و میتونی بعد از اینکه فهمیدی توکن هست با سرور ارتباط برقرار کنی که valid هست یا نه
اگر valid هست که ادامه کار در غیر این صورت ریدایرکتش کنی به صفحه ورود