Login not going to HomeScreen - reactjs

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

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.

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;

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

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

Component not updating/rerendering when redux toolkit state changes

I'm using redux toolkit to manage state and am finding that the components are not updating when changes are made to the state.
I do see though, that when I listen to changes in my redux state within a useEffect that it will trigger the callback, meaning it is aware that the redux state has changed but the component is not rerendering.
Reading other questions it seems like a lot of the issues were about mutating the state, but I do know that using redux tool kit allows you to write "mutable" code and this is handled by Immer. Not sure if this is an issue that applies here...
My Slice:
const initialState = {
watchlists: []
}
export const watchlistsSlice = createSlice({
name: 'watchlists',
initialState,
reducers: {
updateWatchlists: (state, { payload }) => {
state.watchlists = payload;
},
},
})
export const { updateWatchlists } = watchlistsSlice.actions;
export default watchlistsSlice.reducer;
This is the component that calls the function that changes the state:
import React from 'react';
import { StyleSheet, View, Image } from 'react-native';
import { useSelector, useDispatch } from 'react-redux';
import Text from '../core/Text';
import Pressable from '../core/Pressable';
import { AddIcon } from '../core/Icons';
import { formatPrice, formatPercent } from '../../utils/formatNumber';
import { shortenLongText } from '../../utils/formatText';
import { updateWatchlists } from '../../redux/watchlistsSlice';
import { addToWatchlist } from '../../storage/watchlists';
export default function ListItem({data, theme, navigation, watchlistID }) {
const dispatch = useDispatch();
const { currency } = useSelector(state => state.userPreference)
const addCryptoToWatchlist = async () => {
if (watchlistID) {
addToWatchlist(watchlistID, {
slug: data.slug,
})
.then(result => dispatch(updateWatchlists(result)))
.catch(err => console.log(err))
} else {
console.log('not ready yet')
}
}
return (
<Pressable
onPress={() => navigation.navigate('CoinDetails', {
data,
})}
>
<View style={styles.searchResult}>
<View style={styles.nameContainer}>
<Image style={styles.image} source={{uri: data.logo}} />
<View style={{marginLeft: 15}}>
<Text type={"big"} size={18} theme={theme.text}>{data.symbol}</Text>
<Text type={"regular"} size={14} theme={theme.text} style={{paddingTop: 1}}>{shortenLongText(data.name,25)}</Text>
</View>
</View>
<View style={styles.rightContainer}>
<View style={styles.priceContainer}>
<Text type={"big"} theme={theme.text}>{formatPrice(data.price, currency)}</Text>
<Text type={"big"} theme={data.direction === 'up' ? theme.percent.up : theme.percent.down}>{formatPercent(data.percent_change_24h)}</Text>
</View>
<Pressable onPress={() => addCryptoToWatchlist()}>
<AddIcon
size={30}
/>
</Pressable>
</View>
</View>
</Pressable>
)
}
const styles = StyleSheet.create({
searchResult: {
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center',
marginBottom: 30,
},
nameContainer : {
flexDirection: 'row',
alignItems: 'center',
},
rightContainer: {
flexDirection: 'row',
alignItems: 'center',
},
priceContainer: {
alignItems: 'flex-end',
marginRight: 20
},
image: {
width: 28,
height: 28,
}
})
This is one the components that I expect to rerender when the state changes:
The useEffect does get trigged so the component is recognizing a change in state, but the component does not rerender.
I dont know if this is insightful, but the data in the state is an array of objects and in this case a single property one of the objects is getting changed.
import React, { useState, useEffect } from 'react';
import { View, StyleSheet } from 'react-native';
import { useSelector } from 'react-redux';
import GetStarted from './GetStarted';
import AddCryptoCard from './AddCryptoCard';
import CardList from './CardList';
import Text from '../core/Text';
export default function WatchlistCardsSection({ setModalVisible, navigation }) {
const { theme } = useSelector(state => state.userPreference);
const { watchlists } = useSelector(state => state.watchlists)
const { cryptoData } = useSelector(state => state.cryptoData);
const [ watchlistCryptoDataLoaded, setWatchlistCryptoDataLoaded ] = useState(false);
const checkIfWatchlistDataLoaded = () => {
const watchlistNames = watchlists.map(watchlist => watchlist.name);
const checkIfLoaded = cryptoData.map(data => watchlistNames.some(name => data.tags.includes(name))).includes(true);
setWatchlistCryptoDataLoaded(checkIfLoaded);
}
useEffect(() => {
checkIfWatchlistDataLoaded();
},[cryptoData])
useEffect(() => console.log("watchlist updated"), [watchlists])
return (
watchlists &&
watchlists.length === 0 ?
<GetStarted
setModalVisible={setModalVisible}
/>
:
watchlists.filter(item => item.viewOnHome).map(watchlist => (
watchlist.data.length === 0 ?
<AddCryptoCard
key={watchlist.id}
id={watchlist.id}
name={watchlist.name}
navigation={navigation}
/>
:
watchlistCryptoDataLoaded ?
<View
key={watchlist.id}
style={styles.sectionContainer}
>
<Text style={{paddingLeft: 20}} type={'big'} size={24} theme={theme.text}>{watchlist.name}</Text>
<CardList
name={watchlist.name}
config={{type: 'price'}}
navigation={navigation}
/>
</View>
: null
))
)
}
const styles = StyleSheet.create({
sectionContainer: {
flex: 1,
marginTop: 25,
}
})

React native Element type is invalid . Expected a string or class/function but got undefined

Hello friends I have a react native project which showing
and here is my sidebarscreen code
import React,{useState,useEffect} from 'react'
import {View,Text,StyleSheet,ScrollView,ImageBackground,Image,AsyncStorage,TouchableOpacity} from 'react-native'
import {DrawerNavigatorItems as DrawerNavigatorItems} from 'react-navigation-drawer'
// import MainScreen from './MainScreen'
import {Ionicons} from 'react-native-vector-icons'
import {Feather} from 'react-native-vector-icons'
const SidebarScreen = (props) =>{
const [email,setEmail] = useState('loading')
const [name,setName] = useState('loading')
const [mobile,setMobile] = useState('loading')
const [isLoaded,setIsloaded] = useState(false);
useEffect(() => {
async function fetchData() {
setIsloaded(true)
const token = await AsyncStorage.getItem('token');
fetch('http://127.0.0.1:3000',{
headers:new Headers({
Authorization:'Bearer '+token
})
}).then(res=>res.json())
.then(data=>{
setIsloaded(true)
console.log(data)
setEmail(data.email)
setName(data.name)
setMobile(data.mobile)
})
}
fetchData();
}, []); // Or [] if effect doesn't need props or state
const logout = (props) =>{
// console.log(props);
AsyncStorage.removeItem('token').then(()=>{
props.navigation.replace('Login');
})
}
return(
<ScrollView style={{backgroundColor: '#ffff'}}>
<ImageBackground
source = {require("../../assets/screenback.jpg")}
style={{width:100,padding:16,paddingTop:48}}
>
<Image source={require("../../assets/profile.png")} style={styles.profile} />
<Text style={styles.name}>{name}</Text>
<View style={{flexDirection: 'row'}}>
<Ionicons name= "md-people" size={16} color="rgba(255,255,255,0.8)"/>
</View>
</ImageBackground>
<View style={styles.container}>
<DrawerNavigatorItems {...props}/>
</View>
</ScrollView>
)
};
const styles = StyleSheet.create({
container:{
flex:1,
},
navlink:{
justifyContent: 'center',
color:"gray",
fontWeight: '800',
fontSize: 16,
width: 50,
flex:1,
marginLeft: 30,
fontWeight:'500',
alignItems: 'flex-start'
},
profile:{
width:80,
height:80,
borderRadius: 40,
borderWidth: 3,
borderColor: '#fff'
},
name:{
color:"#fff",
fontSize: 20,
fontWeight: '800',
marginVertical: 8
},
followers:{
color:"rgba(255,255,255,0.8)",
fontSize: 13,
marginRight: 4
}
})
export default SidebarScreen;
and here is my report screetn where I am importing sidebar and all links
import React,{useEffect,useState,Component} from "react";
import { Text, StyleSheet,Button,View,TouchableOpacity,AsyncStorage,ScrollView,SafeAreaView,Image,ImageBackground} from "react-native";
import {FontAwesome5} from 'react-native-vector-icons'
import Timeline from 'react-native-timeline-flatlist'
const ReportScreen = (props) => {
const [email,setEmail] = useState('loading')
const [name,setName] = useState('loading')
const [mobile,setMobile] = useState('loading')
const [u_id,setU_id] = useState('')
const [isLoaded,setIsloaded] = useState(false);
const [state,setState] = useState({selected: null});
const im1 = require('../../assets/43/1.png');
useEffect(() => {
async function fetchData() {
setIsloaded(true)
const token = await AsyncStorage.getItem('token');
fetch('http://127.0.0.1:3000',{
headers:new Headers({
Authorization:'Bearer '+token
})
}).then(res=>res.json())
.then(data=>{
setIsloaded(true)
// console.log(data)
setEmail(data.email)
setName(data.name)
setMobile(data.mobile)
setU_id(data.u_id)
})
}
fetchData();
}, []);
return (
<View style={styles.container1} contentInsetAdjustmentBehavior="automatic">
<SafeAreaView style={{flex:1,marginTop:0}}>
<View style={{flex:1,flexDirection:'row',justifyContent:'center'}}>
</View>
</SafeAreaView
</View>
);
};
const styles = StyleSheet.create({
text: {
fontSize: 30
},
imageContainer:{
flex: 1,
// remove width and height to override fixed static size
width: null,
height: null,
marginTop: 0
},
mainView:{
flex:1,
marginTop:35,
alignItems: 'center',
justifyContent:'center'
},
container1:{
flex:1,
marginTop:20,
},
header:{
backgroundColor: "#f3a0d9",
height:200,
overflow: 'hidden',
position: 'relative',
zIndex: 0,
width:500
// zIndex:0
},
});
export default ReportScreen;
and here is my MainScreen where I am importing SidebarScreen
import React,{Component} from 'react'
import { createAppContainer } from 'react-navigation'
import {createDrawerNavigator} from 'react-navigation-drawer'
import {Dimensions,View,Text,ScrollView} from 'react-native'
import {Feather} from 'react-native-vector-icons'
const { width, height } = Dimensions.get('screen');
import {
ProfileScreen,
MessageScreen,
ActivityScreen,
ListScreen,
ReportScreen,
StatisticScreen,
SignOutScreen,
} from "./Index"
import SidebarScreen from './SidebarScreen'
const DrawerNavigator = createDrawerNavigator({
ReportScreen:{
screen: ReportScreen,
navigationOptions:{
title:"Report",
drawerIcon:({tintColor})=><Feather name="trending-up" size={16} color={tintColor} />
}
},
ProfileScreen:{
screen: ProfileScreen,
navigationOptions:{
title:"Profile",
drawerIcon:({tintColor})=><Feather name="user" size={16} color={tintColor} />
}
},
MessageScreen:{
screen: MessageScreen,
navigationOptions:{
title:"Message",
drawerIcon:({tintColor})=><Feather name="message-square" size={16} color={tintColor} />
}
},
ActivityScreen:{
screen: ActivityScreen,
navigationOptions:{
title:"Activity",
drawerIcon:({tintColor})=><Feather name="activity" size={16} color={tintColor} />
}
},
ListScreen:{
screen: ListScreen,
navigationOptions:{
title:"List",
drawerIcon:({tintColor})=><Feather name="list" size={16} color={tintColor} />
}
},
StatisticScreen:{
screen: StatisticScreen,
navigationOptions:{
title:"Statistic",
drawerIcon:({tintColor})=><Feather name="bar-chart" size={16} color={tintColor} />
}
},
SignOutScreen:{
screen: SignOutScreen,
navigationOptions:{
title:"SignOut",
drawerIcon:({tintColor})=><Feather name="log-out" size={16} color={tintColor} />,
}
},
},
{
//contentComponent:props => <SidebarScreen {...props} />,
contentComponent: (props) =>
<View style={{flex: 1}}>
<ScrollView>
<SidebarScreen {...props} />
</ScrollView>
</View>,
// drawerWidth:Dimensions.get('window').width = 0.80,
drawerWidth: Math.min(height, width) * 0.8,
hideStatusBar: false,
contentOptions:{
activeBackgroundColor:"rgba(212,118,207,0.2)",
activeTintColor:"#531158",
itemsContainerStyle:{
marginTop:16,
marginHorizontal:8
},
}
}
);
export default createAppContainer(DrawerNavigator);
The thing is that when I removed Imagebackground then the first error gone but then the second error comes check the render method of DrawerNavigators.and when I removed DrawerNavigatorItems then the errors vanished . but I want the layout to show with drawer and imagebackground , Any help please

Resources