Ui is getting hang after calling Alert in react native - javascript

//
Here I am calling on alart function onPress on text field .
On calling that fucntion I am trying to open alert and on confirm I am calling onther fucntion .
But its getting hang if I am calling "showAlert1()" . This function is getting call many times
showAlert1 (code,name,version) {
console.log("data alaert abc", code,name,version);
Alert.alert(
'Confirmation',
'Are you sure you want to migrate this tariff',
[
{
text: 'Cancel',
onPress: () => console.log('Cancel Pressed'),
style: 'Cancel',
},
{text: 'Proceed', onPress: () =>this.confirmTariffMigration(code,name,version)},
]
);
}
confirmTariffMigration =(code,name,version) =>{
console.log("hhhhdhhdhdhdhhdd",code,name,version);
const objData={
addofferingActionCode:'',
offeringCode:'',
offeringName:''
}
this.props.updateTariffMigration(objData)
}
/////////////////////////////////////////////////////////
<View style={{ marginLeft: 5, marginRight: 5,marginTop:10,backgroundColor:'#f1f1f1' }}>
{ tariffMigrationData.map(
(data, index) => {
return (
// <TouchableOpacity key={index} onPress={this.showAlert1(data)}>
<View style={{ marginBottom: 10, marginLeft: 5, marginRight: 5 }} key={index}>
<Card>
<CardItem header style={{ backgroundColor: '#fff', width: '100%', justifyContent: 'space-between', borderBottomColor: '#f1f1f1', borderBottomWidth: 1 }}>
<View style={{ flexDirection: 'column', justifyContent: 'space-between' }}>
<View>
<RegularText text={`${data.offering.name}`} style={{ fontWeight: 'bold' }} />
<SmallText text={` ID ${data.offering.code}`} textColor="grey" />
</View>
</View>
<View style={{
backgroundColor: 'blue',
borderRadius: 75, height: 25, paddingRight: 10, paddingLeft: 10, paddingTop: 5
}} >
<SmallText text={'Proceed'} onPress={this.showAlert1(data.offering.code,data.offering.version,data.offering.name)} textColor='white' />
</View>
</CardItem>

when we want to pass params to props, here are two ways:
<TouchableOpacity key={index} onPress={() => this.showAlert1(data)}>
<TouchableOpacity key={index} onPress={this.showAlert1.bind(this,data)}>
/////////////////////////////////////
<TouchableOpacity key={index} onPress={this.showAlert1(data)}>

Related

How to print this API response data in React Native?

I want to print this data on my mobile screen but it shows me nothing when I write the code from this response:
This is my code:
const [data, setData] = useState('')
useEffect(() => {
getData()
}, [])
const getData = async () => {
fetch(`${urldemo}blog/${slug}?token=${user_token}`, {
method: 'GET',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
})
.then((response) => response.json())
.then((responseJson) => {
setLoading(false);
setData([...data, ...responseJson.result]);
console.log("log for Exploreblogs =====>", responseJson.result)
})
.catch((error) => {
console.error(error);
});
}
This is my return code where I am stuck:
const renderItem = ({ item }) => {
return (
<ScrollView style={[styles.footer, {
backgroundColor: "white"
// colors.background
}]}>
<Card style={{ marginHorizontal: 20, }}>
<Card.Cover style={{ marginVertical: 10, borderRadius: 10, height: 200, }}
source={require('../../../assets/imagehere.png')} />
<View style={{ flexDirection: 'row', justifyContent: 'space-between' }}>
<Image
source={require('../../../assets/news9.png')} />
<Text style={{ textAlign: 'right', color: "orange" }}>
{item.short_description}
</Text>
</View>
<Text style={{ textAlign: 'center', color: "black", fontSize: 24 }}>
{item.description}
</Text>
<View style={{
justifyContent: "space-between",
flexDirection: "row",
marginHorizontal: 10
}}>
<View style={{ flexDirection: "row" }}>
<Text style={{ color: "green" }}>4hrs ago</Text>
<Text style={{ color: "green" }}> ~ 5 min read</Text>
</View>
<View style={{ flexDirection: "row" }}>
<Image
source={require('../../../assets/comment.png')} />
<Image style={{ marginHorizontal: 10 }}
source={require('../../../assets/shae.png')} />
<Image
source={require('../../../assets/saved.png')} />
</View>
</View>
</Card>
{/* <Text style={{
textAlign: 'left', color: "grey", fontSize: 16,
marginHorizontal: 20, marginVertical: 20
}}>
{item.title}
</Text> */}
<Image style={{ marginHorizontal: 20, width: "90%", borderRadius: 10 }}
source={require('../../../assets/exnews.png')} />
<Text style={{ marginHorizontal: 20 }}>{item.description}</Text>
<Text style={{
textAlign: 'left', color: "grey", fontSize: 16,
marginHorizontal: 20, marginVertical: 20
}}>
{item.short_description}
</Text>
</ScrollView>
);
}
return (
<TouchableOpacity >
{/* <BlogsHeader />
*/}
<Animatable.View
animation="zoomIn" >
<View style={{
flexDirection: 'row',
flexWrap: 'wrap',
justifyContent: 'space-between',
backgroundColor: 'white',
height: 45,
}}>
<TouchableOpacity onPress={() => navigation.navigate('Blogs')}>
<Image style={{
color: 'black',
marginTop: 15,
tintColor: 'orange'
}}
source={require('../../../assets/backicon.png')}
/>
</TouchableOpacity>
<Text style={{
fontSize: 15,
color: '#FF7F23',
textAlign: "center",
marginTop: 15,
}}
> Blogs</Text>
<Image style={{ color: 'black', marginTop: 15, alignSelf: 'center', }}
source={require('../../../assets/avatar.png')}
/>
</View>
{isLoading ? <ActivityIndicator size="large" color="#FF8025" /> : (
<FlatList
style={styles.container}
data={data}
renderItem={renderItem}
keyExtractor={(item, index) => index.toString()}
/>
)
}
</Animatable.View>
</TouchableOpacity>
)
I have used Flatlist for Item.
I just want to print my response data on my mobile screen but it didn't
work for me
I get following error message in the console output:
[TypeError: Invalid attempt to spread non-iterable instance. In order to be iterable, non-array objects must have a Symbol.iterator method.]
The problem is with this line:
setData([...data, ...responseJson.result]);
I'm assuming responseJson.result is an object, in which case this won't work since you can't spread an object into an array, at least in the way you intend.
This should work for you though:
const [data, setData] = useState({}) // Use object instead
// Other stuff
setData({...data, ...responseJson.result}); // Spread to object instead.
Alternatively, consider checking out these solutions e.g. for...of or Object.keys()/entries()/....
Otherwise, you would need to post the value responseJson.result for more troubleshooting.

ERROR : undefined is not an object (evaluation 'style.width')

Hello everyone I'm having trouble with component and I get an undefined error message.So my app has 2 screen,the first one has a list of imagebackgrounds and when you press on one of the images you get a description of that image on another screen.So on this second screen I get the image that I pressed on in an image component (not background).
The problem I'm having is that when I save I get the undefined error.
First screen component :
const MealItems = (props) => {
return (
<View style={styles.main}>
<TouchableOpacity onPress={props.onSelectMeal}>
<View>
<View style={{ ...styles.details, ...styles.maintitle }}>
<ImageBackground
//resizeMode={"center"}
source={{ uri: props.image }}
style={styles.imagebg}
>
<View style={styles.textContainer}>
<Text style={styles.title} numberOfLines={1}>
{props.title}
</Text>
</View>
</ImageBackground>
</View>
<View style={{ ...styles.details, ...styles.info }}>
<Text>{props.duration}</Text>
<Text>{props.complexity.toUpperCase()}</Text>
<Text>{props.affordability.toUpperCase()}</Text>
</View>
</View>
</TouchableOpacity>
</View>
);
};
styles = StyleSheet.create({
main: {
height: 200,
width: "100%",
backgroundColor: "#f5f5f5",
borderRadius: 20,
overflow: "hidden",
marginVertical: 10,
},
maintitle: {
height: "85%",
},
title: {
fontSize: 20,
color: "white",
textAlign: "center",
},
details: {
flexDirection: "row",
},
imagebg: {
width: "100%",
height: "100%",
},
info: {
backgroundColor: "gray",
paddingHorizontal: 10,
justifyContent: "space-between",
alignItems: "center",
height: "15%",
},
textContainer: {
paddingHorizontal: 12,
paddingVertical: 10,
backgroundColor: "rgba(0,0,0,0.3)",
},
});
export default MealItems;
***Second screen file:***
const howToCook = (props) => {
const availableMeals = useSelector((state) => state.Meals.filteredMeals);
const mealId = props.navigation.getParam("mealId");
const selectedMeal = availableMeals.find((meal) => mealId === meal.id);
return (
<ScrollView>
<Image source={{ uri: selectedMeal.imageUrl }} style={styles.image} />
<View style={styles.textDetail}>
<Text>{selectedMeal.duration}</Text>
<Text>{selectedMeal.complexity.toUpperCase()}</Text>
<Text>{selectedMeal.affordability.toUpperCase()}</Text>
</View>
<View style={styles.titlePlace}>
<Text style={styles.textTitle}>Ingredients</Text>
</View>

FlatList RefreshControl not working on Android

I have a FlatList inside of a view and I'm unable to get the refresh control working on Android emulators/devices.
I have tried many solutions but to no luck. Any help or suggestions would be greatly appreciated.
Code:
onPullToRefresh = () => {
this.props.onRefreshData();
}
...
render() {
const isRefreshing = this.props.refreshing['entities'] ? this.props.refreshing['entities'] : false;
...
{!this.state.favoritesExpand &&
<View style={{ flex: 1, flexDirection: 'column', justifyContent: 'center' }}>
<FlatListCustom
style={{ flex: 1, flexDirection: 'column' }}
data={this.state.searchString && this.state.searchString.length > 0 ? this.state.searchMatchedItems : this.state.items}
renderItem={this.renderEntityItem}
keyExtractor={(item) => item.id}
extractData={this.state.selectedItemId}
windowSize={1}
ref={ref => this.itemScrollViewRef = ref}
getItemLayout={this.getItemLayout}
refreshControl={
<RefreshControl refreshing={isRefreshing} onRefresh={this.onPullToRefresh} />
}
/>
{(screenMaster == 'investor' || screenMaster == 'asset') &&
<View style={{ position: 'absolute', right: 0, top: 0, justifyContent: 'space-between', flex: 1, flexDirection: 'column', height: '100%', paddingTop: 8, paddingBottom: 20 }}>
{this.state.AZList.map(item => (
<Touch
key={`AZList_${item}`}
onPress={() => this.onAZListSelect(item)}
>
<Text style={{ textAlign: 'center', color: '#006dc4', fontSize: Platform.isPad ? normalize(7) : normalize(12), paddingHorizontal: 10, fontWeight: 'bold', fontFamily: "Geogrotesque" }}>{item}</Text>
</Touch>
))}
</View>
}
</View>
}

multiline header - React Native

I have a React Native App.
I want to add a subtitle below my header.
Something like this
Header Code:
static navigationOptions = ({ navigation }) => {
return {
title: localizedTitle(),
headerTintColor: '#fff',
headerStyle: {
backgroundColor: isUndercareMode() ? getUndercareColor() : 'rgb(255,0,0)'
},
headerTitleStyle: {
fontWeight: 'bold',
textAlign: 'center',
fontSize: normalizeFontSize(18),
flex: 1
},
headerLeft: <BackButton
accessible={false}
testID='LeftButton'
accessibilityLabel="headerLeftButton"
/>,
headerRight: (<View></View>),
}
}
How can I implement this multiline header?
Update:
I tried 2 ways and both are so frustrating.
1st method:
the back button and user details are not aligned. the back button is moved up.
static navigationOptions = ({ navigation }) => {
return {
title: localizedTitle(),
headerTintColor: '#fff',
headerStyle: {
backgroundColor: HAGo_isUndercareMode() ? HAGo_getUndercareColor() : 'rgb(255,0,0)'
},
headerTitleStyle: {
fontWeight: 'bold',
textAlign: 'center',
fontSize: normalizeFontSize(18),
flex: 1
},
headerLeft: (
<View>
<HAGo_BackButton
accessible={false}
testID='LeftButton'
accessibilityLabel="headerLeftButton"
/>
{
HAGo_isUndercareMode() ?
<View >
<View style={{flexDirection: 'row', backgroundColor:'#008A20', width:500, alignItems:'center'}}>
<Image style={{ width:40, height:40, marginRight:15}} source={require('../HAGo/default_userIcon.png')} />
<Text style={{fontSize: normalizeFontSize(18), color:'#fff'}}>{getUndercareName()}</Text>
</View>
</View>
: null
}
</View>
),
headerRight: (<View></View>),
}
}
2nd method:
not able to align them to the left.
static navigationOptions = ({ navigation }) => {
return {
headerTitle: () =>
<View>
<Text style={{color: '#fff', fontSize:normalizeFontSize(18), fontWeight:'bold'}} >{localizedTitle()}</Text>
<View style={{flexDirection: 'row', justifyContent: 'flex-start'}}>
<Image style={{ width:40, height:40, marginRight:15}} source={require('../HAGo/default_userIcon.png')} />
<Text style={{fontSize: normalizeFontSize(18), color:'#fff'}}>{getUndercareName()}</Text>
</View>
</View>,
headerTintColor: '#fff',
headerStyle: {
backgroundColor: HAGo_isUndercareMode() ? HAGo_getUndercareColor() : 'rgb(255,0,0)'
},
headerTitleStyle: {
fontWeight: 'bold',
textAlign: 'center',
fontSize: normalizeFontSize(18),
flex: 1
},
headerLeft: <HAGo_BackButton
accessible={false}
testID='LeftButton'
accessibilityLabel="headerLeftButton"
/>,
headerRight: (<View></View>),
}
}
Which method makes sense?? Please help.
2nd Update:
static navigationOptions = ({ navigation }) => {
return {
title: localizedTitle(),
headerTintColor: '#fff',
headerStyle: {
backgroundColor: isUndercareMode() ? getUndercareColor() : 'rgb(255,0,0)'
},
headerTitleStyle: {
fontWeight: 'bold',
textAlign: 'center',
fontSize: normalizeFontSize(18),
flex: 1
},
headerLeft: (
<View>
<View style={{paddingTop: isUndercareMode() ? 45 : 0}} >
<BackButton
accessible={false}
testID='LeftButton'
accessibilityLabel="headerLeftButton"
/>
</View>
{
isUndercareMode() ?
<Undercare />
: null
}
</View>
),
headerRight: (<View></View>),
}
}
Undercare component:
export default class Undercare extends React.Component {
render() {
return (
<View>
<View style={{flexDirection: 'row', width:500, height:58, alignItems:'center', paddingLeft:25, backgroundColor:'#008A20', paddingTop:15, paddingBottom:20, backgroundColor:'#008A20'}}>
<Image style={{ width:50, height:50, marginRight:20}} source={require('../HAGo/default_userIcon.png')} />
<Text style={{fontSize: normalizeFontSize(18), color:'#fff'}}>{getUndercareName()}</Text>
</View>
</View>
)
}
}
The back button is not correctly aligned with Notification centre title :/
You can create a custom header component and pass that as an option in order to overwrite the default header.
See this snack for a working example: https://snack.expo.io/#zayco/header-styles_custom
Replace all of the old header options with header
<NavigationContainer>
<Stack.Navigator>
<Stack.Screen
name="Home"
component={HomeScreen}
options={{
header: () => renderHeader()
}}
/>
</Stack.Navigator>
</NavigationContainer>
Add the function to render the custom header
const renderHeader = () => (
<View style={styles.header}>
<View style={styles.headerTop}>
<View style={styles.headerLeft}>
<Text>Back</Text>
</View>
<View style={styles.headerCenter}>
<Text style={styles.headerTitle}>Notification Center</Text>
</View>
<View style={styles.headerRight} />
</View>
<View style={styles.subHeader}>
<View style={styles.subHeaderLeft}>
<Text>ICON</Text>
</View>
<View style={styles.subHeaderCenter}>
<Text style={styles.subHeaderName}>CHUI, Tai Hung</Text>
</View>
</View>
</View>
)
Add the styles used by the custom header. You can play around with the styles to fit your needs.
const styles = {
header: {
flex: 0,
backgroundColor: 'green',
marginTop: Platform.OS == "ios" ? 20 : 0, // only for IOS to give StatusBar Space
padding: 10,
},
headerTop: {
flexDirection: 'row',
},
headerLeft: {
flex: 1,
backgroundColor: 'red',
justifyContent: 'center',
},
headerCenter: {
flex: 6,
alignItems: 'center',
},
headerTitle: {
fontSize: 18,
color: 'white',
fontWeight: 'bold',
},
headerRight: {
flex: 1,
},
subHeader: {
flexDirection: 'row',
paddingTop: 10,
},
subHeaderLeft: {
backgroundColor: 'yellow',
padding: 5,
},
subHeaderCenter: {
justifyContent: 'center',
alignItems: 'center',
},
subHeaderName: {
color: 'white',
marginLeft: 10,
}
}
instead of using title use headerTitle in which you can add a component instead of a string.
static navigationOptions = ({ navigation }) => {
return {
headerTitle: () =>
<View>
<Text>{localizedTitle()}</Text>
<Text>subtitle</Text>
</View>,
headerTintColor: '#fff',
headerStyle: {
backgroundColor: isUndercareMode() ? getUndercareColor() : 'rgb(255,0,0)'
},
headerTitleStyle: {
fontWeight: 'bold',
textAlign: 'center',
fontSize: normalizeFontSize(18),
flex: 1
},
headerLeft: <BackButton
accessible={false}
testID='LeftButton'
accessibilityLabel="headerLeftButton"
/>,
headerRight: (<View></View>),
}
}

React-Native .js Variable not found error

Cannot figure out why I keep getting a ReferenceError cant find variable MarkAsRead for a mobile app I am building in react. Unless I am missing something the variable has been assigned below is the code for your reference. Hopefully, someone can help me get this bug resolved in a timely matter thanks in advance!
import React from 'react';
import { View,
Text,
StyleSheet,
SafeAreaView,
TouchableOpacity,
TextInput,
FlatList
} from 'react-native';
import BookCount from './components/BookCount';
import {Ionicons} from '#expo/vector-icons';
class App extends React.Component {
constructor() {
super()
this.state = {
totalCount: 0,
readingCount: 0,
readCount: 0,
isAddNewBookVisible:false,
textInputData: '',
books: [],
bookData: {
author: '',
publisher: ''
}
};
}
showAddNewBook = () => {
this.setState({isAddNewBookVisible:true});
};
hideAddNewBook = () => {
this.setState({isAddNewBookVisible:false})
};
addBook = book => {
this.setState(
(state, props) => ({
books: [...state.books, book],
totalCount: state.totalCount + 1,
readingCount:state.readingCount + 1,
isAddNewBookVisible: false
}),
() => {
console.log(this.state);
}
);
};
markAsRead = (selectedBook, index) => {
let newList = this.state.books.filter(book => book !==
selectedBook);
this.setState(prevState => ({
books: newList,
readingCount: prevState.readingCount - 1,
readCount: prevState.readCount + 1
}));
};
renderItem = (item, index) => (
<View style={{ height:50, flexDirection: 'row'}}>
<View style={{ flex:1, justifyContent: 'center', paddingLeft: 5
}}>
<Text>{item}</Text>
</View>
<TouchableOpacity onPress={() => markAsRead(item,index)} >
<View
style={{
width: 100,
height: 50,
alignItems: 'center',
justifyContent: 'center',
backgroundColor: '#160b1a'
}}
>
<Text style={{ fontWeight: 'bold', color: 'white'}}>Mark as Read</Text>
</View>
</TouchableOpacity>
</View>
);
render() {
return (
<View style={{flex: 1}}>
<SafeAreaView/>
<View style={{
height: 70,
borderBottomWidth: 0.5,
borderBottomColor: '#5e3c7d',
alignItems: 'center',
justifyContent: 'center'
}}
>
<Text style={{fontSize: 24}}>VekTorfy AI</Text>
</View>
<View style={{ flex: 1}}>
{this.state.isAddNewBookVisible &&
<View style={{height:50, flexDirection: 'row'}}>
<TextInput
onChangeText={(text)=>this.setState({textInputData:text})}
style={{ flex:1, backgroundColor: '#c6c0cb',
paddingLeft: 5}}
placeholder='Enter book name.'
placeholderTextColor='black'
/>
<TouchableOpacity
onPress={() => this.addBook(this.state.textInputData)} >
<View style={{
width: 50,
height: 50,
alignItems: 'center',
justifyContent: 'center',
backgroundColor: '#160b1a'}}>
<Ionicons name ='ios-checkmark' color='white' size={40}/>
</View>
</TouchableOpacity>
<TouchableOpacity onPress={this.hideAddNewBook}>
<View style={{
width: 50,
height: 50,
alignItems: 'center',
justifyContent: 'center',
backgroundColor: '#160b1a'}}>
<Ionicons name ='ios-close' color='red' size={40}/>
</View>
</TouchableOpacity>
</View>
}
<FlatList
data={this.state.books}
renderItem={({item}, index) => this.renderItem(item, index)}
keyExtractor={(item, index)=> index.toString()}
ListEmptyComponent={
<View style={{marginTop: 50, alignItems: 'center'}}>
<Text style={{fontWeight: 'bold'}}>Not Reading anything.</Text>
</View>
}
/>
<TouchableOpacity
onPress={this.showAddNewBook}
style={{position: 'absolute', bottom: 20, right: 20}}>
<View
style={{
width:50,
heght:50,
alignItems: 'center',
justifyContent: 'center',
borderRadius:25,
backgroundColor: '#2d2337'}}>
<Text style={{color: 'white', fontSize: 30}}>+</Text>
</View></TouchableOpacity>
</View>
<View
style={{
height: 70,
flexDirection: 'row',
borderTopWidth: 0.5,
borderTopColor: '#5e3c7d' }}>
<BookCount title='Total' count={this.state.totalCount}/>
<BookCount title='Reading' count={this.state.readingCount}/>
<BookCount title='Read' count={this.state.readCount}/>
</View>
<SafeAreaView/>
</View>
);
}
}
export default App;
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center'
}
});
You forgot to add the keyword this to your function call.
<TouchableOpacity onPress={() => this.markAsRead(item,index)}>
It looks like you have declared markAsRead as a method on your App class, so the correct way to refer to it is this.markAsRead()
<TouchableOpacity onPress={() => this.markAsRead(item, index)}>

Categories

Resources