Hook Error After Implementing Redux Toolkit into Authentication - javascript

I keep getting an error when I run my app, and the screen is just white.
ERROR Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem., js engine: hermes
ERROR Invariant Violation: Module AppRegistry is not a registered callable module (calling runApplication). A frequent cause of the error is that the application entry file path is incorrect.
This can also happen when the JS bundle is corrupt or there is an early initialization error when loading React Native., js engine: hermes
ERROR Invariant Violation: Module AppRegistry is not a registered callable module (calling runApplication). A frequent cause of the error is that the application entry file path is incorrect.
This can also happen when the JS bundle is corrupt or there is an early initialization error when loading React Native., js engine: hermes
Full code is available on my GitHub, but let I'll past the areas of the code I was fiddling with:
https://github.com/astuertz/hashtagValues/commits/master
First, here's my store.js:
import { configureStore } from '#reduxjs/toolkit';
import activeImgReducer from '../features/counter/activeImgSlice';
import userAuthReducer from '../features/counter/userAuthSlice';
export default configureStore({
reducer: {
activeImg: activeImgReducer,
user: userAuthReducer
}
})
Here's my index.js:
/**
* #format
*/
import React from 'react';
import {AppRegistry} from 'react-native';
import App from './App';
import {name as appName} from './app.json';
import store from './src/app/store';
import { Provider } from 'react-redux';
const reduxApp = () => (
<Provider store={store}>
<App />
</Provider>
);
AppRegistry.registerComponent(appName, () => reduxApp);
And my App.js (without styles):
import React from 'react';
import {View, Text, StyleSheet} from 'react-native';
import Navigation from './src/components/routes/navigation';
import Amplify from 'aws-amplify';
import config from './src/aws-exports';
import { withAuthenticator } from 'aws-amplify-react-native';
Amplify.configure({
...config,
Analytics: {
disabled: true,
},
});
const App = () => {
return (
<View style={styles.root}>
<Navigation />
</View>
);
};
Here's my navigation.js (everything from the root stack down--the root stack has several other stacks nested in it):
const RootStack = createNativeStackNavigator();
const RootStackScreen = () => {
const [isLoading, setIsLoading] = useState(true);
const [user, setUser] = useState(null);
useEffect(() => {
setTimeout(() => {
setIsLoading(!isLoading);
setUser('user');
}, 2500)
}, []);
return (
<RootStack.Navigator screenOptions={{
animationEnabled: false,
headerShown: false,
presentation: 'modal',
}}>
{isLoading ? (
<RootStack.Screen name="LoadingScreen" component={LoadingScreen} />
) : user ? (
<RootStack.Screen name="AppTabs" component={AppTabsScreen} />
) : (
<RootStack.Screen name="AuthStackScreen" component={AuthStackScreen} />
)}
<RootStack.Screen name="Gallery" component={GalleryScreen} options={{
animationEnabled: true,
cardStyle: {
backgroundColor: 'black',
},
}}/>
</RootStack.Navigator>
);
};
export default () => {
return (
<NavigationContainer>
<RootStackScreen />
</NavigationContainer>
);
};
I now have it back to the way I had it before the error started occurring.
The only other thing I was messing with is the Sign In Screen and the Profile Screen (with Sign Out). Here's the Sign In Screen:
import React, {useState} from 'react';
import {
View,
Text,
StyleSheet,
Image,
Dimensions,
TextInput,
Button,
TouchableWithoutFeedback,
Keyboard,
TouchableOpacity,
Alert,
} from 'react-native';
import logo from '../../graphics/Values_logo.png';
import { useNavigation } from '#react-navigation/native';
import { Auth } from 'aws-amplify';
import { useSelector, useDispatch, } from 'react-redux';
import { validateUser } from '../../features/counter/userAuthSlice';
const WIDTH = Dimensions.get("window").width;
const HEIGHT = Dimensions.get("window").height;
const SignIn = () => {
const navigation = useNavigation();
const dispatch = useDispatch();
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const onPressSignIn = async () => {
if (email.length < 1 || password.length < 1) return Alert.alert('no input', 'please input an email and password to log in.');
try {
const u = await Auth.signIn(email, password);
dispatch(validateUser(u));
} catch(e) {
Alert.alert('Login Failed!', e.message);
return;
}
Alert.alert('Login Successful!');
return;
}
const renderLogo = (
<Image
source={logo}
style={styles.logoSize}
resizeMode='contain'
/>
);
const inputElements = (
<>
<TextInput
placeholder='email'
value={email}
onChangeText={setEmail}
style={styles.textInput}
/>
<TextInput
placeholder='password'
value={password}
onChangeText={setPassword}
style={styles.textInput}
secureTextEntry={true}
/>
<TouchableOpacity
onPress={onPressSignIn}
style={styles.button}
>
<Text style={styles.buttonText}>Sign In</Text>
</TouchableOpacity>
<Text
style={styles.hyperlink}
>Forgot Password?</Text>
<Text
style={styles.hyperlink}
onPress={() => navigation.push("SignUp")}
>Sign Up</Text>
</>
);
return (
<TouchableWithoutFeedback
onPress={() => Keyboard.dismiss()}>
<View style={styles.pageContainer}>
<View style={styles.logo}>
{renderLogo}
</View>
<View style={styles.inputContainer} >
{inputElements}
</View>
</View>
</TouchableWithoutFeedback>
);
}
And the Profile Screen:
import React from 'react';
import {View, Text, StyleSheet, Button, Alert,} from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { Auth } from 'aws-amplify';
import { useSelector, useDispatch, } from 'react-redux';
import { signOutUser } from '../../features/counter/userAuthSlice';
const dispatch = useDispatch();
const onSignOut = async () => {
try {
await Auth.signOut();
dispatch(signOutUser());
} catch (error) {
Alert.alert('error signing out: ', error.message);
return;
}
Alert.alert('Sign Out Successful!');
}
const ProfileScreen = () => {
return (
<SafeAreaView style={styles.pageContainer}>
<Text>ProfileScreen</Text>
<Button title="Sign Out" onPress={onSignOut} />
</SafeAreaView>
);
};
const styles = StyleSheet.create({
root: {
flex: 1
},
pageContainer: {
justifyContent: 'center',
alignItems: 'center',
flex: 1,
width: '100%'
}
});
export default ProfileScreen;
I'm really not sure what I did to break my app or how to fix it.

In Profile Screen, you are calling const dispatch = useDispatch(); which is outside of the component and is an invalid call. It has to be called in inside ProfileScreen. When you are not sure where the problem occurs try commenting you code and see if it works without them. Like commenting your screens one by one would help you find which screen the error is caused in etc.

Related

Getting an error while trying to call for a child component

I am building a RegisterScreen for my app and I have this child component called `LogResContainer' where I have a component that I share between my login and my register screens.
The thing is I think I am calling everything as it should be called and I don't know what's wrong anymore.
Here is the RegisterScreen.js:
import {
KeyboardAvoidingView,
StyleSheet,
Text,
TextInput,
TouchableOpacity,
View
} from 'react-native'
import React, {useState}from 'react'
import { createUserWithEmailAndPassword } from 'firebase/auth';
import { auth } from '../firebase.js';
import { styles } from '../styles/styles.js';
import {LogResContainer} from './LogResContainer.js';
const RegisterScreen = () => {
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const handleSignup = () => {
createUserWithEmailAndPassword(auth, email, password)
.then(userCredential => {
const user = userCredential.user;
console.log(user.email);
})
.catch(error => alert(error.message));
}
console.log(setEmail);
console.log(setPassword);
console.log(handleSignup);
console.log("Registrar");
return (
<LogResContainer
setEmail={setEmail}
setPassword={setPassword}
type='Registrar'
func={handleSignup}
/>
);
}
export default RegisterScreen
And here is LogResContainer.js:
import {styles} from '../styles/styles.js';
export default LogResContainer = ({setEmail, setPassword, type, func}) => {
return (
<KeyboardAvoidingView style={styles.container} behavior="padding">
<View style={styles.inputContainer}>
<TextInput
placeholder="Email"
value={email}
onChangeText={(text) => setEmail(text)}
style={styles.input}
/>
<TextInput
placeholder="Password"
value={password}
onChangeText={(text) => setPassword(text)}
style={styles.input}
secureTextEntry
/>
</View>
<View style={styles.buttonContainer}>
<TouchableOpacity onPress={func} style={styles.button}>
<Text style={styles.buttonText}>{type}</Text>
</TouchableOpacity>
</View>
</KeyboardAvoidingView>
);
};
I have studied the props docs and looked at multiple youtube videos but I am pretty much exhausted. Don't know what I am missing.
You export LogResContainer as default export, but try to import it like a named export.
Either change the export to a named export:
export const LogResContainer = () => <>"I am a named export"</>
Or change the import to import the default:
import LogResContainer from "./LogResContainer.js"
And if you don't know the difference between named and default exports, read it here: https://www.geeksforgeeks.org/what-is-export-default-in-javascript/
And please add the errors you get, so we can help you better.

ERROR The action 'NAVIGATE' with payload {...} was not handled by any navigator in React Native

I have implemented AWS custom UI authenctication in my react native app and React navigation to navigate through the different screens.
While implementing the logical conditions to see if the "User is already logged in or not" I have assigned the screen "Home" for logged in user and screen 'Login' for not logged in user it's working fine and navigating as expected but the console is showing this error when clicking on login button.
ERROR The action 'NAVIGATE' with payload {"name":"Home"} was not handled by any navigator.
Here is the Navigation code:
import React, {useEffect, useState} from 'react'
import {ActivityIndicator, Alert, View} from 'react-native';
import HomeScreen from '../screens/HomeScreen';
import LoginScreen from '../screens/LoginScreen';
import RegisterScreen from '../screens/RegisterScreen';
import ConfirmEmailScreen from '../screens/ConfirmEmailScreen';
import ForgotPassword from '../screens/ForgotPassword';
import NewPasswordScreen from '../screens/NewPasswordScreen';
import { NavigationContainer } from '#react-navigation/native'
import { createNativeStackNavigator } from '#react-navigation/native-stack';
import {Auth, Hub} from 'aws-amplify';
const Stack = createNativeStackNavigator();
const Navigation = () => {
const [user, setUser] = useState(undefined);
//Checking if user is already logged in or not!
const checkUser = async () => {
try {
const authUser = await Auth.currentAuthenticatedUser({bypassCache: true});
setUser(authUser);
} catch(e) {
setUser(null);
}
};
useEffect(() => {
checkUser();
}, []);
useEffect(() => {
const listener = data => {
if (data.payload.event === 'signIn' || data.payload.event === 'signOut') {
checkUser();
}
}
Hub.listen('auth', listener);
return () => Hub.remove('auth', listener);
}, []);
if (user === undefined) {
return (
<View style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}>
<ActivityIndicator/>
</View>
);
}
return (
<NavigationContainer>
<Stack.Navigator>
{/*{If user is logged in navigate him to Homescreen else go throght the Screens based on the user selection */}
{user ? (
<Stack.Screen name='Home' component={HomeScreen}/>
) : (
<>
<Stack.Screen name='Login' component={LoginScreen}/>
<Stack.Screen name='Register' component={RegisterScreen}/>
<Stack.Screen name='ConfirmEmail' component={ConfirmEmailScreen}/>
<Stack.Screen name='ForgotPassword' component={ForgotPassword}/>
<Stack.Screen name='NewPassword' component={NewPasswordScreen}/>
</>
)}
</Stack.Navigator>
</NavigationContainer>
);
};
export default Navigation;
Here is the Login Screen:
import React, {useState} from 'react'
import { View, Text, Image, StyleSheet, useWindowDimensions, TouchableWithoutFeedback, Keyboard, Alert, KeyboardAvoidingView, ScrollView } 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 {Auth} from 'aws-amplify';
import {useForm} from 'react-hook-form';
const LoginScreen = () => {
const [loading, setLoading] = useState(false);
const {height} = useWindowDimensions();
const {control, handleSubmit, formState: {errors}} = useForm();
const navigation = useNavigation();
const onLoginPressed = async (data) => {
if(loading) {
return;
}
setLoading(true);
try {
await Auth.signIn(data.username, data.password);
navigation.navigate('Home');
} catch(e) {
Alert.alert('Opps', e.message)
}
setLoading(false);
};
const onForgotPasswordPressed = () => {
navigation.navigate('ForgotPassword');
}
const onRegisterPressed = () => {
navigation.navigate('Register')
}
return (
<KeyboardAvoidingView behavior={Platform.OS === "ios" ? "padding" : "height"} style={styles.container}>
<ScrollView contentContainerStyle={{flexGrow:1, justifyContent:'center'}} showsVerticalScrollIndicator={false}>
<TouchableWithoutFeedback onPress={Keyboard.dismiss}>
<View style={styles.root}>
<Image source={Logo} style={[styles.logo, {height : height * 0.2}]} resizeMode={'contain'} />
<CustomInput icon='user' name='username' placeholder='Username' control={control} rules={{required: 'Username is required'}} />
<CustomInput icon='lock' name='password' placeholder='Password' control={control} rules={{required: 'Password is required'}} secureTextEntry={true} />
<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>
</TouchableWithoutFeedback>
</ScrollView>
</KeyboardAvoidingView>
);
};
const styles = StyleSheet.create({
root: {
alignItems: 'center',
padding: 20,
},
logo: {
width: 200,
maxWidth: 300,
maxHeight: 300,
},
});
export default LoginScreen;
Issue
At the time you are calling navigation.navigate('Home') there is no screen called in Home in Navigation because of that ternary that checks whether there is a user or not and renders conditionally your screens. That's why React Naviagation is not happy.
Solution
React Navigation's documention tell us that we shouldn't "manually navigate when conditionally rendering screens​". Means you should find a way to call setUser(user) in Login where setUser is the state setter from Navigation component.
To do so we can use a context and for that change Navigation as follow (I added comments where I changed things):
import React, { createContext, useEffect, useState } from "react";
import { ActivityIndicator, View } from "react-native";
import ConfirmEmailScreen from "../screens/ConfirmEmailScreen";
import ForgotPassword from "../screens/ForgotPassword";
import HomeScreen from "../screens/HomeScreen";
import LoginScreen from "../screens/LoginScreen";
import NewPasswordScreen from "../screens/NewPasswordScreen";
import RegisterScreen from "../screens/RegisterScreen";
import { NavigationContainer } from "#react-navigation/native";
import { createNativeStackNavigator } from "#react-navigation/native-stack";
import { Auth, Hub } from "aws-amplify";
const Stack = createNativeStackNavigator();
// Line I added
export const AuthContext = createContext(null);
const Navigation = () => {
const [user, setUser] = useState(undefined);
//Checking if user is already logged in or not!
const checkUser = async () => {
try {
const authUser = await Auth.currentAuthenticatedUser({ bypassCache: true });
setUser(authUser);
} catch (e) {
setUser(null);
}
};
useEffect(() => {
checkUser();
}, []);
useEffect(() => {
const listener = (data) => {
if (data.payload.event === "signIn" || data.payload.event === "signOut") {
checkUser();
}
};
Hub.listen("auth", listener);
return () => Hub.remove("auth", listener);
}, []);
if (user === undefined) {
return (
<View style={{ flex: 1, justifyContent: "center", alignItems: "center" }}>
<ActivityIndicator />
</View>
);
}
return (
// Wrapper I added
<AuthContext.Provider value={{ user, setUser }}>
<NavigationContainer>
<Stack.Navigator>
{/*{If user is logged in navigate him to Homescreen else go throght the Screens based on the user selection */}
{user ? (
<Stack.Screen name="Home" component={HomeScreen} />
) : (
<>
<Stack.Screen name="Login" component={LoginScreen} />
<Stack.Screen name="Register" component={RegisterScreen} />
<Stack.Screen name="ConfirmEmail" component={ConfirmEmailScreen} />
<Stack.Screen name="ForgotPassword" component={ForgotPassword} />
<Stack.Screen name="NewPassword" component={NewPasswordScreen} />
</>
)}
</Stack.Navigator>
</NavigationContainer>
</AuthContext.Provider>
);
};
export default Navigation;
Consume AuthContext from Navigation in Login so you are able to call setUser after login, like below (I added comments where I changed thing):
import { useNavigation } from "#react-navigation/native";
import React, { useContext, useState } from "react";
import {
Alert,
Image,
Keyboard,
KeyboardAvoidingView,
ScrollView,
StyleSheet,
TouchableWithoutFeedback,
useWindowDimensions,
View,
} from "react-native";
import Logo from "../../../assets/images/logo-main.png";
import CustomButton from "../../components/CustomButton/CustomButton";
import CustomInput from "../../components/CustomInput/CustomInput";
import { Auth } from "aws-amplify";
import { useForm } from "react-hook-form";
// Line I added
import {AuthContext} from "./Navigation" // ⚠️ use the correct path
const LoginScreen = () => {
// Line I added
const { setUser } = useContext(AuthContext);
const [loading, setLoading] = useState(false);
const { height } = useWindowDimensions();
const {
control,
handleSubmit,
formState: { errors },
} = useForm();
const navigation = useNavigation();
const onLoginPressed = async (data) => {
if (loading) {
return;
}
setLoading(true);
try {
const user = await Auth.signIn(data.username, data.password);
// Line I added
setUser(user);
} catch (e) {
Alert.alert("Opps", e.message);
}
setLoading(false);
};
const onForgotPasswordPressed = () => {
navigation.navigate("ForgotPassword");
};
const onRegisterPressed = () => {
navigation.navigate("Register");
};
return (
<KeyboardAvoidingView
behavior={Platform.OS === "ios" ? "padding" : "height"}
style={styles.container}
>
<ScrollView
contentContainerStyle={{ flexGrow: 1, justifyContent: "center" }}
showsVerticalScrollIndicator={false}
>
<TouchableWithoutFeedback onPress={Keyboard.dismiss}>
<View style={styles.root}>
<Image
source={Logo}
style={[styles.logo, { height: height * 0.2 }]}
resizeMode={"contain"}
/>
<CustomInput
icon="user"
name="username"
placeholder="Username"
control={control}
rules={{ required: "Username is required" }}
/>
<CustomInput
icon="lock"
name="password"
placeholder="Password"
control={control}
rules={{ required: "Password is required" }}
secureTextEntry={true}
/>
<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>
</TouchableWithoutFeedback>
</ScrollView>
</KeyboardAvoidingView>
);
};
const styles = StyleSheet.create({
root: {
alignItems: "center",
padding: 20,
},
logo: {
width: 200,
maxWidth: 300,
maxHeight: 300,
},
});

How to display all images from firebase storage on React Native app?

I can upload pictures to FB storage. But now I'm trying to display them all on React Native app live.
For some reason, I can't make it work. There are not lots of videos on youtube or recent tutorials on how to do this. I'm trying to make it work by looking it up on Stackoverflow from people who had some similar problems, but no luck so far.
Here's my app code
import { StyleSheet, View } from 'react-native';
import Uploadscreen from './src/UploadSreen';
import ListPictures from './src/ListPictures';
export default function App() {
return (
<View style={styles.container}>
<Uploadscreen/>
<ListPictures/>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1
}
});
The UploadScreen component works totally fine (this is the one uploading to FB)
And here's my separate component for looping all the images in firebase storage(Which I need help with).
import { firebase } from '../config'
import { View, Image } from 'react-native';
import React, { useState } from 'react';
import 'firebase/compat/auth';
import 'firebase/compat/firestore';
import 'firebase/compat/storage';
const ListPictures = () => {
const [sampleImage, setSampleImage] = useState();
const getSampleImage = async () => {
const imageRefs = await firebase.storage().ref().child('Front/').listAll();
const urls = await Promise.all(imageRefs.items.map((ref) => ref.getDownloadURL()));
setSampleImage(urls);
}
{ sampleImage && getSampleImage().map(url => (
<View style={{ justifyContent: 'center' }} key={imageRef.id}>
<Image source={{ uri: url }} style={{ width: 350, height: 350 }} />
</View>
))}
}
export default ListPictures;
Any help would be much appreciated!
Try this
import { firebase } from '../config'
import { View, Image } from 'react-native';
import React, { useState, useEffect } from 'react';
import 'firebase/compat/auth';
import 'firebase/compat/firestore';
import 'firebase/compat/storage';
const ListPictures = () => {
const [sampleImage, setSampleImage] = useState([]);
const getSampleImage = async () => {
const imageRefs = await firebase.storage().ref().child('Front/').listAll();
const urls = await Promise.all(imageRefs.items.map((ref) => ref.getDownloadURL()));
setSampleImage(urls);
}
useEffect(()=>{
getSampleImage()
},[])
{ sampleImage.length!=0 && sampleImage.map(url => (
<View style={{ justifyContent: 'center' }} key={imageRef.id}>
<Image source={{ uri: url }} style={{ width: 350, height: 350 }} />
</View>
))}
}
export default ListPictures;
You shouldn't call asynchronous code while building the UI output as you do here:
{ sampleImage && getSampleImage().map(url => (
What you have will be called on every render, which is likely not what you want.
Instead, put such a call in a useEffect hook with an empty dependencies array:
useEffect(() => {
getSampleImage();
}, []);
This way the call to getSampleImage() runs when the component gets created, rather than on each render.

Error in render method of App.js? React-Native question

Pasted below is my code:
import React, {useState} from 'react';
import {View, StyleSheet, Flatlist, Alert} from 'react-native';
import 'react-native-get-random-values';
import {v4 as uuidv4} from 'uuid';
import {AddTask} from './src/screens/AddTask';
import {TaskList} from './src/screens/TaskList';
const App = () => {
const [tasks, setTasks] = useState([{id: uuidv4(), text: 'Task 1'}]);
const deleteTask = (id) => {
setTasks((prevTasks) => {
return prevTasks.filter((task) => task.id != id);
});
};
const addTask = (text) => {
if (!text) {
Alert.alert('Error', 'Please enter a task', {text: 'Ok'});
} else {
setTask((prevTask) => {
return [{id: uuid(), text}, ...prevTask];
});
}
};
return (
<View style={styles.container}>
<AddTask addTask={addTask} />
<Flatlist
data={tasks}
renderItem={({task}) => (
<TaskList item={task} deleteTask={deleteTask} />
)}
/>
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
paddingTop: 10,
},
});
export default App;
I get an error about my render method:
ERROR Warning: React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.
After Googling a bit people told me to check my imports, but I swear they are done correctly. Could someone help me understand this? I am building a task manager and I am looking to implement Redux later but I am simply seeking to build the app first: add redux later.
Full Github Project: https://github.com/calebdockal/TaskManagerApp2
There are few changes to be done in the code.
In the import statement remove curly brackets around AddTask and TaskList
import AddTask from './src/screens/AddTask';
import TaskList from './src/screens/TaskList';
Change Flatlist to FlatList in import statement
import {View, StyleSheet, FlatList, Alert} from 'react-native';
and change in return statement. Then update variable in renderItem from task to item and item to task as show below
<FlatList data={tasks}
renderItem={({item}) => (
<TaskList task={item} deleteTask={deleteTask} />
)}
/>
Full code below
import React, {useState} from 'react';
import {View, StyleSheet, FlatList, Alert, Text} from 'react-native';
import 'react-native-get-random-values';
import {v4 as uuidv4} from 'uuid';
import AddTask from './src/screens/AddTask';
import TaskList from './src/screens/TaskList';
const App = () => {
const [tasks, setTasks] = useState([{id: uuidv4(), text: 'Task 1'}]);
const deleteTask = (id) => {
setTasks((prevTasks) => {
return prevTasks.filter((task) => task.id != id);
});
};
const addTask = (text) => {
if (!text) {
Alert.alert('Error', 'Please enter a task', {text: 'Ok'});
} else {
setTasks((prevTask) => {
return [{id: uuidv4(), text}, ...prevTask];
});
}
};
return (
<View style={styles.container}>
<AddTask addTask={addTask} />
<FlatList
data={tasks}
renderItem={({item}) => (
<TaskList task={item} deleteTask={deleteTask} />
)}
/>
)}
/>
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
paddingTop: 10,
},
});
export default App;
I have taken your code from github and updated the code. You can check here
https://snack.expo.io/FbOC0J!MM
You need to add import React from 'react' at top of your code

How to use react hooks on react-native with react-navigation

This is App.js using react-navigation. There are two screens on it called HomeScreen and AddScreen.
import * as React from 'react';
import { NavigationContainer } from '#react-navigation/native';
import { createStackNavigator } from '#react-navigation/stack';
import HomeScreen from './src/HomeScreen';
import AddScreen from './src/AddScreen';
const Stack = createStackNavigator();
function App() {
return (
<NavigationContainer>
<Stack.Navigator initialRouteName="Home">
<Stack.Screen name="Home" component={HomeScreen} />
<Stack.Screen name="Add" component={AddScreen} />
</Stack.Navigator>
</NavigationContainer>
);
}
export default App;
And This is home Screen. There is a 'items' in 'useState. It is gived through Add by navigation as props.
import * as React from 'react';
import PropTypes from 'prop-types';
import { View, Text, Button } from 'react-native';
function HomeScreen({ navigation, route }) {
const [items, setItems] = React.useState([]);
React.useEffect(() => {
if (route.params?.items) {
// Post updated, do something with `route.params.post`
// For example, send the post to the server
console.log('saved');
}
}, [route.params?.items]);
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Button
title="Create post"
onPress={() => navigation.navigate('Add', { items, setItems })}
/>
<View>
{items.map((item, i) => {
return (
<View>
<Text>{item.itemName}</Text>
<Text>{item.itemPrice}</Text>
</View>
);
})}
</View>
</View>
);
}
HomeScreen.propTypes = {
navigation: PropTypes.object.isRequired,
};
export default HomeScreen;
And AddScreen receives 'items' as route.params.
And it use 'setItems' to push his own data in it.
After adding, navigation return to HomeScreen with items that is added with new item.
import * as React from 'react';
import PropTypes from 'prop-types';
import { View, Text, Button, TextInput } from 'react-native';
function AddScreen({ route, navigation }) {
const { items, setItems } = route.params;
const [itemName, setItemName] = React.useState('');
const [itemPrice, setItemPrice] = React.useState('0');
const addItem = () => {
setItems([...items, { itemName, itemPrice }]);
setItemName('');
setItemPrice('0');
};
return (
<View>
<TextInput
multiline
placeholder="What's on your mind?"
value={itemName}
onChangeText={setItemName}
/>
<TextInput
multiline
placeholder="What's on your mind?"
value={itemPrice}
onChangeText={setItemPrice}
/>
<Button
title="Done"
onPress={() => {
addItem();
// Pass params back to home screen
navigation.navigate('Home', items);
}}
/>
</View>
);
}
AddScreen.propTypes = {
navigation: PropTypes.object.isRequired,
route: PropTypes.object.isRequired,
};
export default AddScreen;
It works well on my purpose.
But I'm not sure whether this way is correct or not using react hooks to give and receive data from parent to child.
Could you modify my code ?
You should consider using React Context API https://uk.reactjs.org/docs/context.html. Its dedicated to sharing the common state (items in your case). Here is an example:
You should create a common context for items:
ItemsState.js
import React, { useState, useContext } from 'react';
const ItemsContext = React.createContext([]);
export const ItemsProvider = ({ children }) => {
return (
<ItemsContext.Provider value={useState([])}>
{children}
</ItemsContext.Provider>
);
}
export const useItems = () => useContext(ItemsContext);
Then share the context between screens with provider in App.js like this
import {ItemsProvider} from 'ItemsState';
function App() {
return (
<ItemsProvider> // share the items between both screens
<NavigationContainer>
<Stack.Navigator initialRouteName="Home">
<Stack.Screen name="Home" component={HomeScreen} />
<Stack.Screen name="Add" component={AddScreen} />
</Stack.Navigator>
</NavigationContainer>
</ItemsProvider>
);
}
Then use items context in each screen like this AddScreen.js
import {useItems} from './ItemsState';
function AddScreen({ route, navigation }) {
const [items, setItems] = useItems(); // <- using items context as global useState
const [itemName, setItemName] = React.useState('');
const [itemPrice, setItemPrice] = React.useState('0');
const addItem = () => {
setItems([...items, { itemName, itemPrice }]);
setItemName('');
setItemPrice('0');
};
return (
<View>
<TextInput
multiline
placeholder="What's on your mind?"
value={itemName}
onChangeText={setItemName}
/>
<TextInput
multiline
placeholder="What's on your mind?"
value={itemPrice}
onChangeText={setItemPrice}
/>
<Button
title="Done"
onPress={() => {
addItem();
// Pass params back to home screen
navigation.navigate('Home', items);
}}
/>
</View>
);
}
You can also use useReducer hook and make more Redux-like. Check out this article
https://medium.com/simply/state-management-with-react-hooks-and-context-api-at-10-lines-of-code-baf6be8302c
in order to share data between components you can use Context API or Redux, passing full objects through navigation routes is an anti-pattern, you can find more information in the docs
https://reactnavigation.org/docs/params/#what-should-be-in-params

Categories