pass barcode data to another screen in react native - javascript

I am new to react native I want to ask that if i wanted to show the data from the barcode after scanned to another screen. how to do it here is my code
App.js
import Scanner from './jscan/Scanner';
import Home from './jscan/Home';
import{NavigationContainer} from '#react-navigation/native';
import {createStackNavigator} from '#react-navigation/stack';
import{createBottomTabNavigator} from '#react-navigation/bottom-tabs';
const Stack = createStackNavigator();
const Tab= createBottomTabNavigator();
function App(){
return(
<Stack.Navigator>
<Stack.Screen name="Home" component={Home}/>
<Stack.Screen name="Scanner" component={Scanner}/>
</Stack.Navigator>
);
}
export default () => {
return(
<NavigationContainer>
<App/>
</NavigationContainer>
)
}
here is my Home.js it is the place that i wanted to show my barcode data and also it is the first screen
Home.js
import {View,Text, Button, StyleSheet} from 'react-native';
import React, {useState,Component} from 'react';
import {useNavigation} from'#react-navigation/native';
import {StatusBar} from'expo-status-bar';
import Scanner from './Scanner';
export default function Home ({route}){
const navigation = useNavigation();
return(
<View style={styles.container}>
<Button title = 'Scan' onPress={()=> navigation.navigate('Scanner')}/>
<Text></Text>
<StatusBar style="auto"/>
</View>
);
}
const styles= StyleSheet.create({
container : {
flex:1,
backgroundColor:'#fff',
alignItems:'center',
justifyContent:'center'
}
})
here is the scanner
scanner.js
import React, { useState, useEffect,Component,onMount} from 'react';
import { Text,TextInput, View, StyleSheet, Button } from 'react-native';
import { BarCodeScanner } from 'expo-barcode-scanner';
import {useNavigation} from'#react-navigation/native';
import {StatusBar} from 'expo-status-bar';
export default function App() {
const [hasPermission, setHasPermission] = useState(null);
const [scanned, setScanned] = useState(false);
const [text, setText] = useState('Not yet scanned')
const [currentDate, setCurrentDate] = useState('');
const navigation = useNavigation();
const askForCameraPermission = () => {
(async () => {
const { status } = await BarCodeScanner.requestPermissionsAsync();
setHasPermission(status === 'granted');
})()
}
// Request Camera Permission
useEffect(() => {
askForCameraPermission();
}, []);
useEffect(() => {
var date = new Date().getDate(); //Current Date
var month = new Date().getMonth() + 1; //Current Month
var year = new Date().getFullYear(); //Current Year
var hours = new Date().getHours(); //Current Hours
var min = new Date().getMinutes(); //Current Minutes
var sec = new Date().getSeconds(); //Current Seconds
setCurrentDate(
date + '/' + month + '/' + year
+ ' ' + hours + ':' + min + ':' + sec
);
}, []);
// What happens when we scan the bar code
const handleBarCodeScanned = ({ type, data }) => {
setScanned(true);
setText(data +'\n'+ currentDate)
};
// Check permissions and return the screens
if (hasPermission === null) {
return (
<View style={styles.container}>
<Text>Requesting for camera permission</Text>
</View>)
}
if (hasPermission === false) {
return (
<View style={styles.container}>
<Text style={{ margin: 10 }}>No access to camera</Text>
<Button title={'Allow Camera'} onPress={() => askForCameraPermission()} />
</View>)
}
// Return the View
return (
<View style={styles.container}>
<View style={styles.barcodebox}>
<BarCodeScanner
onBarCodeScanned={scanned ? undefined : handleBarCodeScanned}
style={{ height: 400, width: 400 }} />
</View>
<Text style={styles.maintext}>{text}</Text>
{
scanned && <Button title={'Scan again?'} onPress={() => setScanned(false)} color='tomato' />
}
{
scanned && <Button title={'OK'} onPress={()=> navigation.navigate('Home')} />
}
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
maintext: {
fontSize: 16,
margin: 20,
},
barcodebox: {
alignItems: 'center',
justifyContent: 'center',
height: 300,
width: 300,
overflow: 'hidden',
borderRadius: 30,
backgroundColor: 'tomato'
}
});
I have tried some method from other source but it still cant work with it. hope u guys help thanks

You can pass the data to Home screen with params.
Scanner.js:
// Pass the text parameter as a second argument to navigate function
<Button title={'OK'} onPress={()=> navigation.navigate('Home', { text })} />
Home.js:
// Accessing the passed parameter
export default function Home ({ route }){
...
return (
...
<Text>{route.params && route.params.text}</Text>
...
)
}
Check out react-navigation documentation for more info:
https://reactnavigation.org/docs/params/

Related

React Native App - Expo SDK 47 I've lost all the TV control (focus)

Since i've made the update of the expo SDK to the sdk 47 and update of all the modules, i've lost all my TV navigation. In fact the focus doesn't work anymore.
I've checked all the code, I don't see any problem. There is no problem on the debugger. I'm quite lost.
Can you help me please.
This is my App.js
import React, {useContext, useEffect} from 'react';
import { NavigationContainer } from '#react-navigation/native';
import { createStackNavigator } from '#react-navigation/stack';
import {Context as AuthContext, Provider as AuthProvider} from './context/authContext';
import {Context as UserContext, Provider as UserProvider} from './context/userContext';
import {GlobalizeProvider, loadCldr, loadMessages} from 'react-native-globalize';
import { globalizeRef } from './services/Globalize';
import * as fr from './locales/fr.json';
import * as en from './locales/en.json';
import LoginScreen from "./screens/LoginScreen";
import BroadcastScreen from "./screens/BroadcastScreen";
import AnimatorListScreen from "./screens/AnimatorListScreen";
import SettingsScreen from "./screens/SettingsScreen";
import EntrantScreen from "./screens/EntrantScreen";
import SplashScreen from "./screens/SplashScreen";
loadCldr(
require('react-native-globalize/locale-data/fr'),
require('react-native-globalize/locale-data/en'),
);
loadMessages({fr, en});
const Stack = createStackNavigator();
const Animator = createStackNavigator();
const AnimatorStack = () => {
return (
<Animator.Navigator initialRouteName="List" screenOptions={{headerShown: false}}>
<Animator.Screen name="List" component={AnimatorListScreen} />
<Animator.Screen name="Broadcast" component={BroadcastScreen} options={{ headerShown: false }} />
<Animator.Screen name="Settings" component={SettingsScreen} />
</Animator.Navigator>
)
}
const Entrant = createStackNavigator();
const EntrantStack = () => {
return (
<Entrant.Navigator initialRouteName="Enter" screenOptions={{headerShown: false}}>
<Entrant.Screen name="Enter" component={EntrantScreen} options={{ headerShown: false }} />
<Entrant.Screen name="Settings" component={SettingsScreen} />
</Entrant.Navigator>
)
}
const App = () => {
const {state: authState, restoreInfos} = useContext(AuthContext);
const {state: userState, restoreLanguage} = useContext(UserContext);
useEffect(() => {
restoreInfos();
restoreLanguage();
}, []);
return (
(authState.loading || !userState.language) ?
// We haven't finished checking for the token yet
<Stack.Screen name="Splash" component={SplashScreen} /> :
<GlobalizeProvider ref={globalizeRef} locale={userState.language}>
<NavigationContainer>
<Stack.Navigator>
{(authState.token == null || authState.userType == null) ?
<Stack.Screen name="SignIn" component={LoginScreen} options={{ headerShown: false }} /> :
authState.userType === 'showman' ?
<Stack.Screen name="Showman" component={AnimatorStack} options={{ headerShown: false }} /> :
<Stack.Screen name="Entrant" component={AnimatorStack} options={{ headerShown: false }} />
}
</Stack.Navigator>
</NavigationContainer>
</GlobalizeProvider>
);
}
export default () => {
return (
<AuthProvider>
<UserProvider>
<App />
</UserProvider>
</AuthProvider>
)
}
And one of my screen :
import React, {useContext, useEffect, useRef, useState} from 'react';
import {Animated, StyleSheet, Text, TouchableOpacity, View} from "react-native";
import {Context as UserContext} from "../context/userContext";
import WebView from "react-native-webview";
import {LongPressGestureHandler, State as gestureState} from 'react-native-gesture-handler';
import {useGlobalize} from "react-native-globalize";
import {Ionicons} from '#expo/vector-icons';
import {useNavigation} from "#react-navigation/native";
import Colours from "../constants/Colours";
import Loader from "../components/Loader";
const EntrantScreen = () => {
const navigation = useNavigation();
const {formatMessage} = useGlobalize();
const {state: userState, getChosenAnimation} = useContext(UserContext);
const [reload, setReload] = useState(0);
const [loading, setLoading] = useState(true);
useEffect(() => {
setLoading(true);
getChosenAnimation().finally(() => {
setLoading(false);
});
}, [reload]);
const reloadNow = () => {
setReload(reload + 1);
}
const goToSettings = () => {
navigation.navigate('Settings');
}
const opacityHandler = useRef(new Animated.Value(0)).current;
const fadeIn = () => {
// Will change fadeAnim value to 1 in 5 seconds
Animated.timing(opacityHandler, {
toValue: 1,
duration: 500,
useNativeDriver: true
}).start();
setTimeout(() => {
Animated.timing(opacityHandler, {
toValue: 0,
duration: 500,
useNativeDriver: true
}).start();
}, 3000);
};
const runFirst = "window.oncontextmenu = function(event) {\n" +
" event.preventDefault();\n" +
" event.stopPropagation();\n" +
" return false;\n" +
"};" +
"document.onselectstart = new Function (\"return false\");" +
"document.documentElement.style.property = 'user-select:none;';" +
"document.getElementsByClassName('aha-footer')[0].remove();";
return (
<View style={styles.mainView}>
{loading && <Loader />}
{ userState.chosenAnimation &&
<View style={styles.mainView}>
<LongPressGestureHandler
minDurationMs={5000}
onHandlerStateChange={({nativeEvent}) => {
if (nativeEvent.state === gestureState.ACTIVE) {
fadeIn();
}
}}>
<View style={styles.actionCaller}><></></View>
</LongPressGestureHandler>
<Animated.View style={{...styles.actionButtonHandler, opacity: (opacityHandler || 0)}}>
<TouchableOpacity onPress={() => reloadNow()}>
<Ionicons style={{color: Colours.bleu}} name="reload" size={48} />
</TouchableOpacity>
<TouchableOpacity onPress={() => goToSettings()}>
<Ionicons style={{color: Colours.bleu}} name="settings-outline" size={48} />
</TouchableOpacity>
</Animated.View>
<WebView
style={styles.container}
source={{uri: userState.chosenAnimation.entrant_link}}
injectedJavaScript={runFirst}
/>
</View>
}
{!loading && !userState.chosenAnimation &&
<View style={styles.viewNoAnim}>
<Text style={styles.textNoAnim}>{formatMessage('noChosenAnim')}</Text>
<View style={styles.viewIconsNoAnim}>
<TouchableOpacity style={styles.iconsNoAnim} onPress={() => reloadNow()}>
<Ionicons style={{color: Colours.bleu}} name="reload" size={48} />
</TouchableOpacity>
<TouchableOpacity style={styles.iconsNoAnim} onPress={() => goToSettings()}>
<Ionicons style={{color: Colours.bleu}} name="settings-outline" size={48} />
</TouchableOpacity>
</View>
</View>
}
</View>
)
}
const styles = StyleSheet.create({
mainView: {
flex: 1
},
actionCaller: {
width: 50,
height: 80,
position: 'absolute',
left: 0,
top: 0,
backgroundColor: 'transparent',
zIndex: 2,
opacity: 0.1
},
actionButtonHandler: {
width: 80,
height: '100%',
position: 'absolute',
left: 0,
top: 0,
justifyContent: 'space-evenly',
alignItems: 'center',
zIndex: 2
},
viewNoAnim: {
flex: 1,
flexDirection: 'column',
justifyContent: 'center',
alignItems: 'center',
},
viewIconsNoAnim: {
flexDirection: 'row',
},
iconsNoAnim: {
margin: 10
},
textNoAnim: {
fontSize: 24
}
});
export default EntrantScreen;
Thanks a lot for your help.

in react-native how to use body-pix

import { Camera, CameraType } from 'expo-camera';
import React, { useRef } from "react";
// import logo from './logo.svg';
import * as tf from "#tensorflow/tfjs";
import * as bodyPix from "#tensorflow-models/body-pix";
import { useState } from 'react';
import { Button, StyleSheet, Text, TouchableOpacity, View } from 'react-native';
//AFTER IMPORT
export default function App() {
const [type, setType] = useState(CameraType.back);
const [permission, requestPermission] = Camera.useCameraPermissions();
const canvasRef = useRef(null);
//next part
const runBodysegment = async () => {
const net = await bodyPix.load();
console.log("BodyPix model loaded.");
// Loop and detect hands
setInterval(() => {
detect(net);
}, 100)
};
//next part
const detect = async (net) => {
const person = await net.segmentPersonParts(video);
console.log(person);
const coloredPartImage = bodyPix.toColoredPartMask(person);
bodyPix.drawMask(
canvasRef.current,
video,
coloredPartImage,
0.7,
0,
false
);
runBodysegment();
if (!permission) {
// Camera permissions are still loading
return <View />;
}
if (!permission.granted) {
// Camera permissions are not granted yet
return (
<View style={styles.container}>
<Text style={{ textAlign: 'center' }}>We need your permission to show the camera</Text>
<Button onPress={requestPermission} title="grant permission" />
</View>
);
}
function toggleCameraType() {
setType(current => (current === CameraType.back ? CameraType.front : CameraType.back));
}
return (
<View style={styles.container}>
<Camera style={styles.camera} type={type}>
<View style={styles.buttonContainer}>
<TouchableOpacity style={styles.button} onPress={toggleCameraType}>
<Text style={styles.text}>Flip Camera</Text>
</TouchableOpacity>
</View>
</Camera>
</View>
);
}
//next part
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
},
camera: {
flex: 1,
},
buttonContainer: {
flex: 1,
flexDirection: 'row',
backgroundColor: 'transparent',
margin: 64,
},
button: {
flex: 1,
alignSelf: 'flex-end',
alignItems: 'center',
},
text: {
fontSize: 24,
fontWeight: 'bold',
color: 'white',
},
});
};
I want to use body-pix in my react-native app for android .
can any one help me how to do it .
I want my app to open a camera and in my camera there will be a body body-pix working
in my android app
I want my react-native app to work properly with body-pix
I had try it many time time but I can't do it properly

React native onPress or any event is not working after sometime of app load

I am using react native thunder push where continually value fluctuation happening and i am showing data on screen using mobx state management tool. all things is working fine but when i am leave the screen for 2 minute then that events are not working screen is not freezing only events is not working.
STORE
import {observable,action,makeAutoObservable} from 'mobx';
class CommonMob {
data =[];
checkAppstate ='active';
deployeStatus = true;
queryString = '?creator_id=null&tags=&exchange=null&broker_id=null&instrument_type=null&execution=null&status=null&pnl=null&broker_id=';
userToken = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOlwvXC9hcGktYXBwLnRyYWRldHJvbi50ZWNoXC9hdXRoXC9zaWduLWluIiwiaWF0IjoxNjU0ODYzMjcyLCJleHAiOjIzNTQ3MDMyNzIsIm5iZiI6MTY1NDg2MzI3MiwianRpIjoicVF6TTJHUkdQS3kyY0NCeCIsInN1YiI6MjY3NTE5LCJwcnYiOiIyM2JkNWM4OTQ5ZjYwMGFkYjM5ZTcwMWM0MDA4NzJkYjdhNTk3NmY3In0.QLDx1SUEJBheQbm-UqD8AOad5Oj3x3UWHBeShmn-2PE';
constructor() {
makeAutoObservable(this)
}
setData(res) {
this.data =res;
}
setAppState(val){
this.checkAppstate = val;
}
setdeployeStatus(val){
this.deployeStatus = val;
}
}
export default new CommonMob()
Screen
import {TouchableOpacity,View, Text, Button, FlatList, AppState,ScrollView,InteractionManager} from 'react-native';
import React, {useCallback, useEffect} from 'react';
import deployedStore from '../mob/deployedStore';
import {useIsFocused, useFocusEffect} from '#react-navigation/native';
import MarketStore from '../mob/deployedStore';
import {observer} from 'mobx-react-lite';
import {initThunderPush} from '../Service/ThunderConnection';
import {
fetchStrategies,
fetchFullStrategies,
} from '../Service/DeployeConnection';
import CommonStore from '../mob/commonStore';
import commonStore from '../mob/commonStore';
import Nav from '../Nav/Nav';
import { useNavigation } from '#react-navigation/native';
// import commonStore from '../mob/commonStore';
let listening = false;
const Deplyee = React.memo(observer(({navigation}) => {
// const navigation = useNavigation();
const navFun = ()=>{
alert("function call");
navigation.navigate("Dashboard")
}
useFocusEffect(
useCallback(() => {
// Do something when the screen is focused.
deployedStore.setisDeploye(true);
deployedStore.setisMarcketWatch(true);
commonStore.setdeployeStatus(true);
return () => {
// Do something when the screen is unfocused
deployedStore.setisDeploye(false);
deployedStore.setisMarcketWatch(false);
commonStore.setdeployeStatus(false);
};
}, []),
);
// React.useEffect(() => {
// }, [deployedStore.dataaa, deployedStore.strategies]);
React.useEffect(
() => {
InteractionManager.runAfterInteractions(() => {
// let timer = setTimeout(() => , 1000)
fetchFullStrategies(CommonStore.userToken);
fetchStrategies();
// fetchFullStrategies(CommonStore.userToken);
initThunderPush();
return () => {
clearTimeout(timer)
}
});
},
[[deployedStore.dataaa, deployedStore.strategies]]
)
React.useEffect(() => {
fetchStrategies();
}, [deployedStore.strategies]);
useFocusEffect(
React.useCallback(() => {
// fetchFullStrategies(CommonStore.userToken);
}, [deployedStore.strategies]),
);
React.useEffect(
() => {
if (!listening) {
initThunderPush();
listening = true;
}
setInterval(() => {
deployedStore.setCanState(true);
}, 1000);
},
[
/*strategies*/
],
);
useEffect(() => {
const appStateListener = AppState.addEventListener(
'change',
nextAppState => {
commonStore.setAppState(nextAppState);
},
);
return () => {
appStateListener?.remove();
};
}, []);
return (
<View>
<ScrollView>
<View
style={{
display: 'flex',
flexDirection: 'row',
width: '100%',
margin: 'auto',
flexWrap: 'wrap',
}}>
<Nav />
<TouchableOpacity onPress={() => alert("test pass")} ><Text>Test alert</Text></TouchableOpacity>
<TouchableOpacity onPress={() => navFun()} >
<Text>test function </Text>
</TouchableOpacity>
</View>
<Text>Deployed Strategies</Text>
{deployedStore.strategies.map(item => (
<View key={item.identifier}>
<Text style={{color: 'red', alignSelf: 'center'}}>
NAME - {item.template.name}
</Text>
<Text style={{color: 'blue', alignSelf: 'center'}}>
TYPE - {item.deployment_type}
</Text>
<Text style={{color: 'green', alignSelf: 'center'}}>
STATUS {item.status}
</Text>
<Text style={{color: 'orange', alignSelf: 'center', fontSize: 20}}>
{/* <Text style={item.sum_of_pnl >= 0 ? {color:green} : {color:red}}> */}
{item.country === 'IN'
? `${(item.sum_of_pnl, 0)} (${(
(item.sum_of_pnl /
(item.template.capital_required * item.minimum_multiple)) *
100
).toFixed(2)} %)`
: null}
</Text>
{/* <Text style={{color:'green', alignSelf:'center'}}>{item.ltp}</Text> */}
</View>
))}
<Text>market watch section</Text>
{deployedStore.dataaa.map(item => (
<View key={item.identifier}>
<Text style={{color: 'red', alignSelf: 'center'}}>
{item.identifier}
</Text>
<Text style={{color: 'green', alignSelf: 'center'}}>{item.ltp}</Text>
</View>
))}
</ScrollView>
</View>
);
}));
export default React.memo(Deplyee);

using Onclick, fetch api data in react native

I am new to React Native.
I am facing an issue with this view. Basically it is something like this when you click a button it generates any random number, now this random number becomes an id and it goes to at the end of the API url, And using this new API - with ID at the end of it. - data gets fetched. Now i've divided this task in two parts generating random number code (i.e. snippet 1) and fetching data from api ( i.e. snippet 2). As of now, I don't know how to combine them because i am new to react native so a little help here would be appreciated from anyone.
Snipppet 1
import { StyleSheet, View, Button, Text } from 'react-native';
export default class MyProject extends Component {
constructor(){
super();
this.state={
// This is our Default number value
NumberHolder : 0
}
}
GenerateRandomNumber=()=>
{
var RandomNumber = Math.floor(Math.random() * 5000) + 1 ;
this.setState({
NumberHolder : RandomNumber
})
}
render() {
return (
<View style={styles.MainContainer} >
<Text style={{marginBottom: 10, fontSize: 20}}>{this.state.NumberHolder}</Text>
<Button title="Generate Random Number" onPress={this.GenerateRandomNumber} />
</View>
);
}
}
const styles = StyleSheet.create(
{
MainContainer: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
}
});
Snippet 2
import React, { useState } from "react";
import { Box, FlatList, Center, NativeBaseProvider, Button } from "native-base";
import { StyleSheet, View, ActivityIndicator, Text, TouchableOpacity, Image } from 'react-native';
export default function MyFUnction() {
const [data, setData] = useState(null);
const [visible, setVisible] = useState(true);
const fetchData = async () => {
const resp = await fetch("https://jsonplaceholder.typicode.com/photos/7");
const data = await resp.json();
setData(data);
setVisible(false);
};
const renderItem = ({ item }) => {
return (
<TouchableOpacity style={styles.list}>
<Text>{item.title}</Text>
</TouchableOpacity>
);
};
return (
<NativeBaseProvider>
<Center flex={1}>
{visible && <Button onPress={() => fetchData()}>Press</Button>}
{data && (
<FlatList
data={data}
renderItem={(item) => this.renderItem(item)}
keyExtractor={(item) => item.id.toString()}
/>
)}
</Center>
</NativeBaseProvider>
);
}
const styles = StyleSheet.create({
list: {
paddingVertical: 4,
margin: 5,
backgroundColor: '#fff',
},
});
Thanks in advance!!
I think you must understand components clearly! React is component based! But your case is not 2 components! You have a component for fetching api and showing in list! Generating a random number is not a component, but it is a method(or function) in your list component! I think it is better to use one component for list and wrap a function to it for generating random number.
import React, { useState } from "react";
import { Box, FlatList, Center, NativeBaseProvider, Button } from "native-base";
import { StyleSheet, View, ActivityIndicator, Text, TouchableOpacity, Image } from 'react-native';
export default function MyFUnction() {
const [data, setData] = useState(null);
const [visible, setVisible] = useState(true);
const generatRandomNumber = () => {
return Math.floor(Math.random() * 5000) + 1
}
const fetchData = async () => {
const resp = await fetch(`https://jsonplaceholder.typicode.com/photos/${generatRandomNumber()}`);
const data = await resp.json();
setData(data);
setVisible(false);
};
const renderItem = ({ item }) => {
return (
<TouchableOpacity style={styles.list}>
<Text>{item.title}</Text>
</TouchableOpacity>
);
};
return (
<NativeBaseProvider>
<Center flex={1}>
{visible && <Button onPress={() => fetchData()}>Press</Button>}
{data && (
<FlatList
data={data}
renderItem={(item) => this.renderItem(item)}
keyExtractor={(item) => item.id.toString()}
/>
)}
</Center>
</NativeBaseProvider>
);
}
const styles = StyleSheet.create({
list: {
paddingVertical: 4,
margin: 5,
backgroundColor: '#fff',
},
});
But if you want to passing data between components you are have, it is not related to function or class component and you can pass data between them with props! So your code like this:
Random Number Component
import { StyleSheet, View, Button, Text } from 'react-native';
export default class MyProject extends Component {
constructor(props){ //edited
super(props); //edited
this.state={
// This is our Default number value
NumberHolder : 0
}
}
GenerateRandomNumber=()=>
{
var RandomNumber = Math.floor(Math.random() * 5000) + 1 ;
this.props.randomNumber(RandomNumber)
}
render() {
return (
<View style={styles.MainContainer} >
<Text style={{marginBottom: 10, fontSize: 20}}>{this.state.NumberHolder}</Text>
<Button title="Generate Random Number" onPress={this.GenerateRandomNumber} />
</View>
);
}
}
const styles = StyleSheet.create(
{
MainContainer: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
}
});
Your list component:
import React, { useState } from "react";
import { Box, FlatList, Center, NativeBaseProvider, Button } from "native-base";
import { StyleSheet, View, ActivityIndicator, Text, TouchableOpacity, Image } from 'react-native';
// import MyProject
export default function MyFUnction() {
const [data, setData] = useState(null);
const [visible, setVisible] = useState(true);
const [number, setNumber] = useState(null);
const fetchData = async () => {
const resp = await fetch(`https://jsonplaceholder.typicode.com/photos/${number}`);
const data = await resp.json();
setData(data);
setVisible(false);
};
const renderItem = ({ item }) => {
return (
<TouchableOpacity style={styles.list}>
<Text>{item.title}</Text>
</TouchableOpacity>
);
};
return (
<NativeBaseProvider>
<Center flex={1}>
<MyProject radomNumber={(number) => setNumber(number)}
{visible && <Button onPress={() => fetchData()}>Press</Button>}
{data && (
<FlatList
data={data}
renderItem={(item) => this.renderItem(item)}
keyExtractor={(item) => item.id.toString()}
/>
)}
</Center>
</NativeBaseProvider>
);
}
const styles = StyleSheet.create({
list: {
paddingVertical: 4,
margin: 5,
backgroundColor: '#fff',
},
});
thanks everyone for helping me.
here i am posting answer to my question, if anybody in future need an answer.
import React, { useEffect, useState, Component } from 'react';
import { StyleSheet, View, Button, FlatList, Text, Image } from 'react-native';
export default class MyProject extends Component {
constructor(){
super();
this.state={
// This is our Default number value
NumberHolder : 1,
books: []
}
}
GenerateRandomNumber=()=>
{
var RandomNumber = Math.floor(Math.random() * 5000) + 1;
fetch(`https://jsonplaceholder.typicode.com/photos/${RandomNumber}`)
.then((response) => response.json())
.then(booksList => {
this.setState({ books: booksList });
});
this.setState({
NumberHolder : RandomNumber
})
}
render() {
let Image_Http_URL ={ uri: 'https://reactnativecode.com/wp-content/uploads/2017/05/react_thumb_install.png'};
return (
<View style={styles.MainContainer} >
<Text style={{marginBottom: 10, fontSize: 20}}>{this.state.NumberHolder}</Text>
<Image
style={{width: '100%', height: 200,resizeMode : 'stretch' }}
source={{uri: this.state.books.url}}
/>
<Text style={{marginBottom: 10, fontSize: 12}}>{this.state.books.title}</Text>
<Text style={{marginBottom: 10, fontSize: 12}}>{this.state.books.url}</Text>
<Text style={{marginBottom: 10, fontSize: 12}}>{this.state.books.thumbnailUrl}</Text>
<Button title="Generate Random Number" onPress={this.GenerateRandomNumber} />
</View>
);
}
}
const styles = StyleSheet.create(
{
MainContainer: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
}
});

React native useEffect does not work when it's in same screen or back to screen

I am using react naviagtion 5 and typescript for my mobile.
I have two sets of data in the database, one is date and one is time. Both are expecting strings.
I made one POST request when the user chooses the date, and that time will be selected for the user. I made a helper function for when the user's choosing time will be over, in which case I show them an alert on the front-end that shows
"Your selected time expired!"
After showing that Alert. I forcefully clear the delivery time. My logic works fine. But I am having issue that when I am in the same screen or minimise the app, the useEffect does not trigger. If I go different screen and come back to that delivery screen then it triggers. I don't know how to hot reload the app when selecting time expired even though I am in the same screen or minimise the app.
I share my code in Expo snack
This is my sample code
import * as React from 'react';
import {Text,View, Alert, Button} from 'react-native';
import { NavigationContainer } from '#react-navigation/native';
import { createStackNavigator } from '#react-navigation/stack';
import { useNavigation } from '#react-navigation/native';
const Stack = createStackNavigator();
const deliveryDate = "2021-06-21";
const deliveryTime = "10:00-10:03";
const isTimeWindowExpired = (date: string, time: string) => {
const [startTime] = time.split('-');
const newDate = new Date(`${date}T${startTime}`);
if (newDate.getTime() < new Date().getTime()) {
return true;
}
return false;
};
function Home() {
const navigation = useNavigation()
return (
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
<Text>Home</Text>
<Button
title="Go to Details"
onPress={() => navigation.navigate('details')}
/>
</View>
);
}
function SecondHome() {
const navigation = useNavigation()
React.useEffect(() => {
const isExpired = isTimeWindowExpired(deliveryDate, deliveryTime);
const expirationTrigger = () => {
Alert.alert("Time Expired");
};
if (isExpired) {
expirationTrigger();
}
}, [deliveryDate, deliveryTime]);
return (
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
<Text>useEffect does not trigger when it's in same screen or minimisse</Text>
<Text>Home</Text>
<Button
title="Go back Home"
onPress={() => navigation.goBack()}
/>
</View>
);
}
const App = () => {
return (
<NavigationContainer>
<Stack.Navigator initialRouteName="home" detachInactiveScreens>
<Stack.Screen name="home" component={Home} />
<Stack.Screen name="details" component={SecondHome} />
</Stack.Navigator>
</NavigationContainer>
);
};
export default App;
Using useIsFocused hook from react-navigation could help you.
It basically checks, if the screen is looked at. Adding it into useEffect and its dependencies, the useEffect will trigger every time isFocused changes its value. When you leave the screen (to another screen or minimizing the app) it's false and when you come back, it is true back again.
import { useIsFocused } from '#react-navigation/native';
function SecondHome() {
const navigation = useNavigation()
const isFocused = useIsFocused();
React.useEffect(() => {
if(isFocused) {
const isExpired = isTimeWindowExpired(deliveryDate, deliveryTime);
const expirationTrigger = () => Alert.alert("Time Expired");
if (isExpired) {
expirationTrigger();
}
}
}, [deliveryDate, deliveryTime, isFocused]);
return (
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
<Text>useEffect does not trigger when it's in same screen or minimisse</Text>
<Text>Home</Text>
<Button
title="Go back Home"
onPress={() => navigation.goBack()}
/>
</View>
);
}
You can read more about it here https://reactnavigation.org/docs/use-is-focused/

Categories