How to print this API response data in React Native? - javascript

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.

Related

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>
}

different color for every item of flatlist based on condition

I want color of every item based on condition like:-
I will have my condition like :- let check = item.project_status.
and check can be completed, in-progress and incomplete.
and red for incomplete, yellow for in-progress and green for completed.
Here is my flatlist code:-
<FlatList
style={{height:constants.DesignHeight - 100}}
data={props.DATA}
renderItem={({ item }) =>
<TouchableOpacity onPress={props.onPress} style={styles.flatlistContainer}>
<View style={{ flexDirection: 'row', justifyContent: 'space-between' }}>
<Text style={styles.text}>{item.project_name} </Text>
<Text style={styles.text2}>Start: {moment(item.start_date).format("DD/MM/YYYY")}</Text>
</View>
<View style={{ flexDirection: 'row', justifyContent: 'space-between' }}>
<Text style={styles.text}>Assigned to: {item.project_manager.name} </Text>
<Text style={styles.text2}>End: {moment(item.end_date).format("DD/MM/YYYY")}</Text>
</View>
<View>
</View>
</TouchableOpacity>
}
KeyExtractor={(item) => item.id}
// ItemSeparatorComponent={() => renderSeparator()}
/>
const styles = StyleSheet.create({
flatlistContainer: {
width: '100%',
},
text: {
fontSize: constants.vw(20),
lineHeight: constants.vw(30),
},
text2: {
fontSize: constants.vw(16),
lineHeight: constants.vw(30),
}
})
How can I achieve this?
Thanks!!!
i think you can make a style for each project status
and you can use it
const styles = StyleSheet.create({
...
incomplete: {
color: 'red'
},
inprogress: {
color: 'yellow'
},
completed: {
color: 'green'
}
}})
and you can use it on style tag
like this
<View style={{ flexDirection: 'row', justifyContent: 'space-between' }}>
<Text style={[styles.text, styles[item.project_status]}>{item.project_name} </Text>
<Text style={[styles.text2, styles[item.project_status]}>Start: {moment(item.start_date).format("DD/MM/YYYY")}</Text>
</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)}>

Ui is getting hang after calling Alert in react native

//
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)}>

Categories

Resources