The action 'NAVIGATE' with payload was not handled by any navigator [React Native] - reactjs

Hello I have 3 drawer Navigators[Home,List,Contact] and I want to navigate from List Screen to an other Screen called EditScreen this Why I create a Stack Navigator on the List Screen But I got an error when I press the name on the table thet should take me to From the List Screen to The Edit Screen.
App.js
import * as React from 'react';
import { NavigationContainer } from '#react-navigation/native';
import { createNativeStackNavigator } from '#react-navigation/native-stack';
import { createDrawerNavigator } from '#react-navigation/drawer';
import COLORS from './src/conts/colors';
import HomeScreen from './Screens/HomeScreen';
import ListScreen from './Screens/ListScreen';
import FormScreen from './Screens/FormScreen';
import EditScreen from './Screens/EditScreen';
const Stack = createNativeStackNavigator();
const Drawer = createDrawerNavigator();
const App = () => {
return (
<NavigationContainer>
<Drawer.Navigator initialRouteName="Home" screenOptions={{
headerStyle: {
backgroundColor: COLORS.lightkBlue
},
headerTintColor: '#fff',
headerTitleStyle: {
fontWeight: 'bold'
}
}}>
<Drawer.Screen name="Home" component={HomeScreen} />
<Drawer.Screen name="List" component={ListScreen} />
<Drawer.Screen name="Form" component={FormScreen} />
</Drawer.Navigator>
</NavigationContainer>
);
}
export default App;
ListScreen.js
import React, { useState } from 'react';
import { StyleSheet, SafeAreaView, ScrollView,Text, View, Modal } from 'react-native';
import { DataTable } from 'react-native-paper';
import { NavigationContainer } from '#react-navigation/native';
import { createNativeStackNavigator } from '#react-navigation/native-stack';
import COLORS from '../src/conts/colors';
import Button from '../src/views/components/Button';
import EditScreen from './EditScreen';
const Stack = createNativeStackNavigator();
function Edit() {
return (
<Stack.Navigator>
<Stack.Screen name="Edit" component={EditScreen} />
</Stack.Navigator>
);
}
const List = ({navigation}) => {
const data = [
{id:1,name:"Hassane1",phone:"068888188888",email:"contact#gemail.com"},
{id:2,name:"Hassane2",phone:"068888888288",email:"contact#gemail.com"},
{id:3,name:"Hassane3",phone:"068888388888",email:"contact#gemail.com"},
]
const renderList = data.map((item)=>{
return(
<DataTable.Row key={item.id}>
<DataTable.Cell onPress={() => navigation.navigate("Edit",{item})} >{item.name}</DataTable.Cell>
<DataTable.Cell>{item.email}</DataTable.Cell>
<DataTable.Cell>{item.phone}</DataTable.Cell>
</DataTable.Row>
)
})
return (
<SafeAreaView style={{backgroundColor: COLORS.white, flex: 1}}>
<ScrollView
contentContainerStyle={{paddingTop: 50, paddingHorizontal: 20}}>
<Text style={{color: COLORS.black, fontSize: 40, fontWeight: 'bold'}}>
List of Companies
</Text>
<Text style={{color: COLORS.grey, fontSize: 18, marginVertical: 10}}>
Check Our Companies Details
</Text>
<DataTable style={styles.container} >
<DataTable.Header style={styles.tableHeader} >
<DataTable.Title>Name</DataTable.Title>
<DataTable.Title>email</DataTable.Title>
<DataTable.Title>Phone</DataTable.Title>
</DataTable.Header>
</DataTable>
{renderList}
</ScrollView>
</SafeAreaView>
);
};
export default List;
const styles = StyleSheet.create({
container: {
padding: 15,
},
tableHeader: {
backgroundColor: '#F3F4FB',
},
modalButtonView: {
}
});
EditScreen.js
import React, { useState } from 'react';
import {
View,
Text,
TextInput,
SafeAreaView,
Keyboard,
ScrollView,
Alert,
} from 'react-native';
import COLORS from '../src/conts/colors';
import Button from '../src/views/components/Button';
import Input from '../src/views/components/Input';
import Loader from '../src/views/components/Loader';
const EditScreen = (props) => {
const {id,name,phone,email} = props.route.params.item
const [inputs, setInputs] = React.useState({
name: '',
email: '',
phone: '',
});
const [errors, setErrors] = React.useState({});
const [loading, setLoading] = React.useState(false);
const validate = () => {
Keyboard.dismiss();
let isValid = true;
if (!inputs.name) {
handleError('Please input Company', 'name');
isValid = false;
}
if (!inputs.email) {
handleError('Please input email', 'email');
isValid = false;
} else if (!inputs.email.match(/\S+#\S+\.\S+/)) {
handleError('Please input a valid email', 'email');
isValid = false;
}
if (!inputs.phone) {
handleError('Please input phone number', 'phone');
isValid = false;
}
{/*if (isValid) {
register();
}*/}
};
const handleOnchange = (text, input) => {
setInputs(prevState => ({...prevState, [input]: text}));
};
const handleError = (error, input) => {
setErrors(prevState => ({...prevState, [input]: error}));
};
return (
<SafeAreaView style={{backgroundColor: COLORS.white, flex: 1}}>
<Loader visible={loading} />
<ScrollView
contentContainerStyle={{paddingTop: 50, paddingHorizontal: 20}}>
<Text style={{color: COLORS.black, fontSize: 40, fontWeight: 'bold'}}>
Edit
</Text>
<Text style={{color: COLORS.grey, fontSize: 18, marginVertical: 10}}>
Now You Can Edit !
</Text>
<View style={{marginVertical: 20}}>
<Input
onChangeText={text => handleOnchange(text, 'name')}
onFocus={() => handleError(null, 'name')}
iconName="account-outline"
label="Company"
placeholder="Enter your Company Name"
error={errors.name}
defaultValue={name}
/>
<Input
onChangeText={text => handleOnchange(text, 'email')}
onFocus={() => handleError(null, 'email')}
iconName="email-outline"
label="Email"
placeholder="Enter your email address"
error={errors.email}
defaultValue={email}
/>
<Input
keyboardType="numeric"
onChangeText={text => handleOnchange(text, 'phone')}
onFocus={() => handleError(null, 'phone')}
iconName="phone-outline"
label="Phone Number"
placeholder="Enter your phone no"
error={errors.phone}
defaultValue={phone}
/>
<Button title="Save" onPress={validate} />
<Button title="Cancel" onPress={() => props.navigation.navigate("List")} />
</View>
</ScrollView>
</SafeAreaView>
);
};
export default EditScreen;
This is The Error
enter image description here

Your 'Edit' navigator is declared in your Edit() function but the function is never called.
react-navigation does know how to navigate to it since it is never initiated
You should try to call the function at least once at component start so the navigator is initiated

You do not have EditScreen as a screen on the drawers navigation screens in App.js
Try to add:
<Drawer.Screen name="Edit" component={EditScreen} />
On App.js

Related

Navigate to another page in React Native

I have difficulty navigate to another page. I want to click Card in Profile page and then it will navigate to page CardHome. I add <NavigationContainer> in apps.js but didnt work. I am newbie so I am not sure where is wrong. Hopefully someone can help me.
This is profile.js
`import React, { useState, useEffect } from 'react'import { Text, View, StyleSheet, SafeAreaView, TouchableOpacity } from 'react-native'
import { firebase } from '../config'import EntypoIcon from "react-native-vector-icons/Entypo";
import { createStackNavigator } from '#react-navigation/stack';import { NavigationContainer } from '#react-navigation/native';import CardHome from '../CardHome';
const Profile = () => {const [name, setName] = useState('')
useEffect (() => {
firebase.firestore().collection('users')
.doc(firebase.auth().currentUser.uid).get()
.then((snapshot) => {
if(snapshot.exists){
setName(snapshot.data())
}
else {
console.log('User does not exist')
}
})
}, [])
return (
<SafeAreaView style={styles.container}>
<Text style={{fontSize:20, fontWeight:'bold', marginLeft:180, marginBottom:-11}}>
{name.username}
</Text>
<TouchableOpacity
onPress={() => navigation.navigate('CardHome')}
style={styles.button3}>
<View style={styles.icon3Row}>
<EntypoIcon name="open-book" style={styles.icon3}></EntypoIcon>
<Text style={styles.card}>CARD</Text>
</View>
</TouchableOpacity>
<TouchableOpacity
onPress={() => {firebase.auth().signOut()}}
style={styles.button5}>
<EntypoIcon name="user" style={styles.icon5}></EntypoIcon>
</TouchableOpacity>
</SafeAreaView>
)
}`
This is my CardHome.js
`import React, { Component } from "react";
import { StyleSheet, View, TouchableOpacity, Text } from "react-native";
import EntypoIcon from "react-native-vector-icons/Entypo";
import { NavigationContainer } from "#react-navigation/native";
import { createStackNavigator } from "#react-navigation/stack";
function CardHome(props) {
return (
<View style={styles.container}>
<View style={styles.buttonRow}>
<TouchableOpacity style={styles.button}>
<Text style={styles.scam}>SCAM</Text>
</TouchableOpacity>
<TouchableOpacity style={styles.button5}>
<EntypoIcon name="magnifying-glass" style={styles.icon5}></EntypoIcon>
<Text style={styles.explore3}>EXPLORE</Text>
</TouchableOpacity>
</View>
<View style={styles.button4Row}>
<TouchableOpacity style={styles.button4}>
<Text style={styles.socialEngineering}>SOCIAL ENGINEERING</Text>
</TouchableOpacity>
<TouchableOpacity style={styles.button3}>
<EntypoIcon name="magnifying-glass" style={styles.icon4}></EntypoIcon>
<Text style={styles.explore2}>EXPLORE</Text>
</TouchableOpacity>
</View>
</View>
);
}
this is my Apps.js
import { NavigationContainer } from "#react-navigation/native";
import { createStackNavigator } from "#react-navigation/stack";
import React, { useState, useEffect } from 'react';
import { firebase } from './config';
import Login from "./src/Login";
import Registration from "./src/Registration";
import Profile from "./src/Profile";
import Header from "./components/Header";
import CardHome from "./CardHome";
const Stack = createStackNavigator();
function App() {
const [initializing, setInitializing] = useState(true);
const [user, setUser] = useState();
function onAuthStateChanged(user) {
setUser(user);
if (initializing) setInitializing(false);
}
useEffect(() => {
const subscriber = firebase.auth().onAuthStateChanged(onAuthStateChanged);
return subscriber;
}, []);
if (initializing) return null;
if (!user) {
return (
<Stack.Navigator>
<Stack.Screen
name="Login"
component={Login}
options={{
headerTitle: () => <Header name="MySecureAwareness" />,
headerStyle: {
height: 150,
borderBottomLeftRadius: 50,
borderBottomRightRadius: 50,
backgroundColor: "#00e4d0",
shadowColor: "#000",
elevation: 25,
}
}}
/>
<Stack.Screen
name="Registration"
component={Registration}
options={{
headerTitle: () => <Header name="MySecureAwareness" />,
headerStyle: {
height: 150,
borderBottomLeftRadius: 50,
borderBottomRightRadius: 50,
backgroundColor: "#00e4d0",
shadowColor: "#000",
elevation: 25
}
}}
/>
</Stack.Navigator>
);
}
return (
<NavigationContainer>
<Stack.Navigator>
<Stack.Screen
name="Profile"
component={Profile}
options={{
headerTitle: () => <Header name="MySecureAwareness" />,
headerStyle: {
height: 150,
borderBottomLeftRadius: 50,
borderBottomRightRadius: 50,
backgroundColor: "#00e4d0",
shadowColor: "#000",
elevation: 25
}
}}
/>
<Stack.Screen
name="CardHome" component={CardHome} />
</Stack.Navigator>
</NavigationContainer>
);
}
export default () => {
return (
<NavigationContainer>
<App />
</NavigationContainer>
)
}
I want to click Card then it will navigate to Cardhome.js.

React Hooks form showing undefined username in logs

I've integrated react hooks form in my react native app and I'm trying to connect the text input with the hooks controller for validation but when I write the username and click on the button it's showing username undefined not sure where the binding gone wrong please check and suggest what should I fix here?
import React, {useState} from 'react'
import { View, Text, Image, StyleSheet, useWindowDimensions, ScrollView, Alert, TextInput } from 'react-native'
import Logo from '../../../assets/images/logo-main.png'
import CustomButton from '../../components/CustomButton/CustomButton';
import CustomInput from '../../components/CustomInput/CustomInput';
import { useNavigation } from '#react-navigation/native';
import {useForm, Controller} from 'react-hook-form';
import { Auth } from 'aws-amplify';
const LoginScreen = () => {
const [loading, setLoading] = useState(false);
const {height} = useWindowDimensions();
const {control, handleSubmit} = useForm();
const navigation = useNavigation();
const onLoginPressed = (data) => {
console.log(data)
// if (loading) {
// return;
// }
// setLoading(true);
// try {
// response = await Auth.signIn(data.username, data.password);
// console.log(response);
// } catch(e) {
// Alert.alert('Opps', e.message);
// }
// setLoading(false);
};
const onForgotPasswordPressed = () => {
navigation.navigate('ForgotPassword');
}
const onRegisterPressed = () => {
navigation.navigate('Register')
}
return (
<ScrollView contentContainerStyle={{ flexGrow: 1, justifyContent: 'center' }} showsVerticalScrollIndicator={false}>
<View style={styles.root}>
<Image source={Logo} style={[styles.logo, {height : height * 0.2}]} resizeMode={'contain'} />
{/* <CustomInput placeholder='Username' />
<CustomInput placeholder='Password' secureTextEntry={true}/> */}
<Controller control={control} name="username" render={({field: value, onChange, onBlur}) =>
<TextInput value={value} onChangeText={onChange} onBlur={onBlur} placeholder='Username' /> } />
<TextInput placeholder='Password'/>
<CustomButton text={loading ? 'Loading...' : 'Login Account'} onPress={handleSubmit(onLoginPressed)} />
<CustomButton text='Forgot Password?' onPress={onForgotPasswordPressed} type='TERTIARY' />
<CustomButton text="Don't have an account? Create one" onPress={onRegisterPressed} type='TERTIARY' />
</View>
</ScrollView>
);
};
const styles = StyleSheet.create({
root: {
alignItems: 'center',
padding: 20,
},
logo: {
width: 200,
maxWidth: 300,
maxHeight: 300,
},
});
export default LoginScreen;
As the react-hook-form approach, you should import the controller from useForm, and then in the controller, you can render a TextInput. Also, in the controller's render attribute, you can use onChange,onBlur and validate your inputs .
import { useForm, Controller } from "react-hook-form";
...
const LoginScreen = () => {
...
const { control, handleSubmit, formState: { errors } } = useForm({
defaultValues: {
username: '',
}
});
...
const onSubmit = data => console.log(data);
return (
<ScrollView contentContainerStyle={{ flexGrow: 1, justifyContent: 'center' }} showsVerticalScrollIndicator={false}>
...
<Controller
control={control}
rules={{
required: true,
}}
render={({ field: { onChange, onBlur, value } }) => (
<TextInput
style={styles.input}
onBlur={onBlur}
onChangeText={onChange}
value={value}
placeholder='Username'
/>
)}
name="username"
/>
...
</ScrollView>
)
}

usecontext without child component?

I'm wanting to pass a state from my WeatherComponent through to my UserForm component and ideally would like to do this without making the UserForm a child component. At the moment I have the UserForm as a child component and that component is working fine when I render it because it's getting the weather state from the WeatherComponent. But now when I want to render my WeatherComponent it renders the UserComponent as well.
Is there another way I could use useContext or a method that doesn't rely on making a child component?
WeatherComponent:
import axios from 'axios';
import { useEffect, useState, createContext } from 'react';
import { Weather } from '../types';
import { MdWbSunny } from 'react-icons/md';
import { IoIosPartlySunny } from 'react-icons/io';
import { BsFillCloudSnowFill } from 'react-icons/bs';
import { Title, Text, Container } from '#mantine/core';
import UserForm from './UserForm';
export const WeatherContext = createContext<any>(null);
const WeatherComponent = () => {
const [weather, setWeather] = useState<Weather | null>();
const fetchWeatherData = async () => {
const response = await axios.get('http://mock-api-call/weather/get-weather');
setWeather(response.data.result.weather);
};
useEffect(() => {
fetchWeatherData();
}, []);
return (
<Container>
<WeatherContext.Provider value={weather?.forcast}>
<UserForm />
</WeatherContext.Provider>
<Title order={2}>
{weather?.forcast === 'Sunny' ? (
<MdWbSunny data-testid="sunny" />
) : weather?.forcast === 'Snowing' ? (
<BsFillCloudSnowFill data-testid="snowing" />
) : (
<IoIosPartlySunny data-testid="overcast" />
)}
</Title>
<Text size="xl" data-testid="forcast">
{weather?.forcast}
</Text>
<Text size="lg" data-testid="temp">
Temp: {`${weather?.min} to ${weather?.max}`}
</Text>
<Text size="md" data-testid="description">
{weather?.description}
</Text>
</Container>
);
};
export default WeatherComponent;
UserForm:
import React, { useContext, useState } from 'react';
import { Container, Title, TextInput, Button, Group, Header } from '#mantine/core';
import { useStateWithLocalStorage } from './UseStateWithLocalStorage';
import { WeatherContext } from './WeatherComponent';
import { MdWbSunny } from 'react-icons/md';
import { BsFillCloudSnowFill } from 'react-icons/bs';
import { IoIosPartlySunny } from 'react-icons/io';
const UserForm = () => {
const [inputValue, setInputValue] = useStateWithLocalStorage('', 'form');
const [show, setShow] = useState(true);
const weatherIcon = useContext(WeatherContext);
function handleChange(event: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) {
setInputValue(() => ({
[event.target.name]: event.target.value,
}));
}
return (
<Header height={56} mb={120}>
<Container
style={{
display: 'flex',
flexDirection: 'row',
backgroundColor: 'gray',
justifyContent: 'space-between',
color: 'white',
alignItems: 'center',
padding: '10px',
fontSize: '25px',
fontWeight: 'bold',
boxShadow: '0 3px 6px 0 #555',
}}
>
<Group>
<Title order={2}>Welcome </Title>
{show && (
<TextInput
type="text"
name="name"
id="name"
placeholder="enter your name"
onChange={handleChange}
value={inputValue.name}
/>
)}
{show && <Button onClick={() => setShow((prev) => !prev)}>SAVE</Button>}
<Title order={2}>{inputValue.name ? inputValue.name : ''}</Title>
</Group>
<Group style={{ display: 'flex', justifyContent: 'flex-end' }}>
<Title order={2}>
{weatherIcon === 'Sunny' ? (
<MdWbSunny data-testid="sunny" />
) : weatherIcon === 'Snowing' ? (
<BsFillCloudSnowFill data-testid="snowing" />
) : (
<IoIosPartlySunny data-testid="overcast" />
)}
</Title>
</Group>
</Container>
</Header>
);
};
export default UserForm;

React navigation 6.x not passing props

I have the code as below, every time i try to pass parameter from Home Page to the Second Page i keep getting undefined, and i never got the props or anything.
This is my app.js file
import React from 'react';
import {
SafeAreaView,
StatusBar,
Text,
View,
} from 'react-native';
import { NavigationContainer } from '#react-navigation/native';
import { createNativeStackNavigator } from '#react-navigation/native-stack';
import Home from './App/screens/home';
import Second from './App/screens/second';
function HomeScreen() {
return (
<Home />
);
}
function OtherScreen() {
return (
<Second />
);
}
const Stack = createNativeStackNavigator();
const App = () => {
return (
<SafeAreaView style={{ flex: 1 }}>
<NavigationContainer>
<Stack.Navigator initialRouteName="Home">
<Stack.Screen
name="Home"
component={HomeScreen}
options={{ title: 'Overview' }} />
<Stack.Screen
name="Second"
component={OtherScreen}
/>
</Stack.Navigator>
</NavigationContainer>
</SafeAreaView>
);
};
export default App;
This is Home Page
import React, { useState } from 'react';
import {
Button,
Dimensions,
Platform,
SafeAreaView,
ScrollView,
StatusBar,
StyleSheet,
Text,
useColorScheme,
View,
} from 'react-native';
import {
Colors,
DebugInstructions,
Header,
LearnMoreLinks,
ReloadInstructions,
} from 'react-native/Libraries/NewAppScreen';
import { useNavigation } from '#react-navigation/native';
const Home = () => {
const isDarkMode = useColorScheme() === 'dark';
const navigation = useNavigation();
const backgroundStyle = {
backgroundColor: isDarkMode ? Colors.darker : Colors.lighter,
};
return (
<SafeAreaView style={backgroundStyle}>
<StatusBar barStyle={isDarkMode ? 'light-content' : 'dark-content'} />
<ScrollView
contentInsetAdjustmentBehavior="automatic"
style={backgroundStyle}>
<Header />
<View
style={{
backgroundColor: isDarkMode ? Colors.black : Colors.white,
}}>
<Button
title="Go to Details"
onPress={() => navigation.navigate('Second', { name: "John Doe" })}
/>
<LearnMoreLinks />
</View>
</ScrollView>
</SafeAreaView>
);
};
const styles = StyleSheet.create({
sectionContainer: {
marginTop: 32,
paddingHorizontal: 24,
},
sectionTitle: {
fontSize: 24,
fontWeight: '600',
},
sectionDescription: {
marginTop: 8,
fontSize: 18,
fontWeight: '400',
},
highlight: {
fontWeight: '700',
},
});
export default Home;
This is the screen named "Second"
import React, { useEffect } from 'react';
import {
SafeAreaView,
ScrollView,
StatusBar,
StyleSheet,
useColorScheme,
} from 'react-native';
import {
Colors,
Header,
} from 'react-native/Libraries/NewAppScreen';
import { useNavigation } from '#react-navigation/native';
const Second = ({ route }) => {
const isDarkMode = useColorScheme() === 'dark';
const navigation = useNavigation();
useEffect(() => {
console.log(route)
})
const backgroundStyle = {
backgroundColor: isDarkMode ? Colors.darker : Colors.lighter,
};
return (
<SafeAreaView style={backgroundStyle}>
<StatusBar barStyle={isDarkMode ? 'light-content' : 'dark-content'} />
<ScrollView
contentInsetAdjustmentBehavior="automatic"
style={backgroundStyle}>
<Header />
</ScrollView>
</SafeAreaView>
);
};
const styles = StyleSheet.create({
sectionContainer: {
marginTop: 32,
paddingHorizontal: 24,
},
sectionTitle: {
fontSize: 24,
fontWeight: '600',
},
sectionDescription: {
marginTop: 8,
fontSize: 18,
fontWeight: '400',
},
highlight: {
fontWeight: '700',
},
});
export default Second;
i have tried a lot of solutions before i post this question most of them is version 4.x or 5.x
You don't need to declare a function to return the screen, just assign to component directly:
const App = () => {
return (
<SafeAreaView style={{ flex: 1 }}>
<NavigationContainer>
<Stack.Navigator initialRouteName="Home">
<Stack.Screen
name="Home"
component={Home}
options={{ title: 'Overview' }} />
<Stack.Screen
name="Second"
component={Second}
/>
</Stack.Navigator>
</NavigationContainer>
</SafeAreaView>
);
};

Login not going to HomeScreen

My login not going to HomeScreen, but when I reload the app it will automatically go to HomeScreen? The login functionality works fine the only thing that bugging me right now, it needs to reload the app before it will go to HomeScreen.
Below are the file for my App, LoadingScreen, LoginScreen, and HomeScreen.
App.js
import React, { useEffect, useState } from 'react';
import { NavigationContainer } from '#react-navigation/native';
import { createStackNavigator } from '#react-navigation/stack';
import SignupScreen from './screens/SignupScreen';
import LoginScreen from './screens/LoginScreen';
import LoadingScreen from './screens/LoadingScreen';
import HomeSceen from './screens/HomeScreen';
import AsyncStorage from '#react-native-community/async-storage';
const App = ({ navigation }) => {
const [isloggedin, setLogged] = useState(null);
const detectLogin = async () => {
const token = await AsyncStorage.getItem('token');
if (token !== null) {
setLogged(true);
} else {
setLogged(false);
}
};
useEffect(() => {
detectLogin();
}, []);
const StackApp = createStackNavigator();
return (
<NavigationContainer>
<StackApp.Navigator headerMode="none">
<StackApp.Screen name="loading" component={LoadingScreen} />
<StackApp.Screen name="home" component={HomeSceen} />
<StackApp.Screen name="login" component={LoginScreen} />
<StackApp.Screen name="signup" component={SignupScreen} />
</StackApp.Navigator>
</NavigationContainer>
);
}
export default App;
LoadingScreen.js
import React, { useEffect } from 'react';
import {
ActivityIndicator,
View,
StyleSheet
} from 'react-native';
import AsyncStorage from '#react-native-community/async-storage';
const LoadingScreen = (props) => {
const detectLogin = async () => {
const token = await AsyncStorage.getItem('token');
if (token) {
props.navigation.replace("home");
} else {
props.navigation.replace("login");
}
};
useEffect(() => {
detectLogin();
}, []);
return (
<View style={styles.loading}>
<ActivityIndicator size="large" color="#ff0550" />
</View>
);
};
const styles = StyleSheet.create({
loading: {
flex: 1,
justifyContent: "center",
alignItems: "center"
},
});
export default LoadingScreen;
LoginScreen.js
import React, { useState } from 'react';
import { Button, TextInput } from 'react-native-paper';
import {
View,
Text,
StatusBar,
TouchableOpacity,
KeyboardAvoidingView,
Alert,
} from 'react-native';
import AsyncStorage from '#react-native-community/async-storage';
import { SafeAreaView } from 'react-native-safe-area-context';
const LoginScreen = (props) => {
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const handleLogin = async (props) => {
fetch('http://localhost:3000/api/auth/login', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
'email': email,
'password': password,
}),
})
.then(res => res.json())
.then(async (data) => {
try {
const items = [['token', data.token], ['user', data.user._id]];
AsyncStorage.multiSet(items);
props.navigation.replace('home');
} catch (e) {
console.log('error log', data.error);
Alert(data.error);
}
});
};
return (
<SafeAreaView style={{ flex: 1 }}>
<KeyboardAvoidingView behavior="position">
<StatusBar backgroundColor="#ff0550" barStyle="light-content" />
<View
style={{
borderBottomColor: '#ff0550',
borderBottomWidth: 4,
borderRadius: 10,
marginLeft: 20,
marginRight: 150,
marginTop: 4,
}}
/>
<Text
style={{
fontSize: 20, marginLeft: 18, marginTop: 20
}}
>Login with email</Text>
<TextInput
label='Email'
autoCapitalize="none"
mode="outlined"
value={email}
style={{ marginLeft: 18, marginRight: 18, marginTop: 18 }}
theme={{ colors: { primary: '#ff0550' } }}
onChangeText={(text) => setEmail(text)}
/>
<TextInput
label='password'
autoCapitalize="none"
mode="outlined"
secureTextEntry={true}
value={password}
onChangeText={(text) => { setPassword(text) }}
style={{ marginLeft: 18, marginRight: 18, marginTop: 18 }}
theme={{ colors: { primary: '#ff0550' } }}
/>
<Button
mode="contained"
style={{ marginLeft: 18, marginRight: 18, marginTop: 18, backgroundColor: '#ff0550' }}
onPress={() => handleLogin(props)}>
Login
</Button>
<TouchableOpacity>
<Text
style={{
fontSize: 18, marginLeft: 18, marginTop: 20
}}
onPress={() => props.navigation.replace('signup')}
>dont have a account ?</Text>
</TouchableOpacity>
</KeyboardAvoidingView>
</SafeAreaView>
);
};
export default LoginScreen;
HomeScreen.js
import React, { useEffect, useState } from 'react';
import { Button } from 'react-native-paper';
import { Text, View } from 'react-native';
import AsyncStorage from '#react-native-community/async-storage';
const HomeScreen = (props) => {
const logout = (props) => {
let keys = ['user', 'token'];
AsyncStorage.multiRemove(keys, (error) => {
props.navigation.replace('login');
});
};
return (
<View style={{ flex: 1, marginTop: 100 }}>
<Text style={{ fontSize: 18 }}>your email is sample here!</Text>
<Button
mode="contained"
style={{ marginLeft: 18, marginRight: 18, marginTop: 18, backgroundColor: '#ff0550' }}
onPress={() => logout(props)}
>
logout
</Button>
</View>
);
};
export default HomeScreen;
user props.navigation.navigate("Homescreen")
Also,you need add condition in app js if logged then go to homescreen else login page.
Check switch Navigator too from react-navigation
Replace just change current screen to another screen instead of navigating through screen. so it will stay that screen only

Resources