not able to map array value in react native - javascript

I am getting below value in the props "ticketDetailsInfo" and after that I am taking followupDetails array ,below is the value of followupDetails which is coming from server . ,but when amd doing maping followupDetails.map() its throwing error followupDetails.map() is not a function . While I have to take array value and display in ui . Please correct me where I am going wrong .
// Array Value is
const{ticketDetailsInfo}=this.props
const{troubleTicketDetails,workFlowDetails,followupDetails} =ticketDetailsInfo;
"followupDetails": [
{
"INCIDENTNUMBER": "16739",
"INCIDENTINITIATOR": "U",
"INCIDENTTIMESTAMP": "06/06/2019 16:25:36",
"NOTES": "Test",
"USERID": "597",
"STATUSUPDATED": null,
"USERGROUPNAME": "clmui",
"BINARYOBJECT": "N"
},
{
"INCIDENTNUMBER": "16738",
"INCIDENTINITIATOR": "E",
"INCIDENTTIMESTAMP": "06/06/2019 16:25:36",
"NOTES": "Test",
"USERID": "597",
"STATUSUPDATED": null,
"USERGROUPNAME": "clmui",
"BINARYOBJECT": "N"
}
],
import React, { Component } from 'react';
import { ImageBackground, ScrollView } from 'react-native';
import { Body, Button, Card, CardItem, Text, View } from 'native-base';
import styles from '../requestTab/TroubleTicketDetails.style';
import Header from '../../ui/header';
import BG from '../../../images/bg.jpg';
import { IconNormal } from '../../ui/icons';
import _ from 'lodash';
import { RegularText, SmallText } from '../../ui/text';
import StepIndicator from 'react-native-step-indicator';
import LoadingSpinner from '../../ui/spinner';
class TroubleTicketDetails extends Component {
constructor(props) {
super(props);
const {MSISDN,ticketDetailsInfo} = this.props;
this.state = {
title: 'Trouble Ticket',
icon: "sim",
mobile: MSISDN,
StepsVaue:[],
Steplabels:[],
currentStepPosition:[],
SteplabelconcatValue:[],
SteplabelsTimes:[]
};
}
iconSymbol = (priority) => {
let symbol = '';
let color = '';
if (priority === '10') {
symbol = 'exclamation';
color = 'red';
} else if (priority === '1') {
symbol = 'arrowdown';
color = 'white';
} else {
symbol = '';
color = '';
}
return { symbol: symbol, color: color };
};
componentDidMount() {}
componentDidUpdate(prevProps, prevState, snapshot) {}
componentDidCatch(error, errorInfo) {
console.log("TroubleTicketHistory Error", error);
console.log("TroubleTicketHistory ErrorInfo", errorInfo);
}
loadScreen() {
//RedirectScreen(this.props.navigation, 'SimSwap', this.state);
}
renderLabel = ({ position, stepStatus, SteplabelsTimes, currentPosition }=this.state) => {
return (
<Text
style={
position === currentPosition ? styles.stepLabelSelected : styles.stepLabel
}
>
{SteplabelsTimes}
</Text>
)
}
render() {
let { title, mobile, icon, currentStepPosition, Steplabels } = this.state;
let { navigation,ticketDetailsInfo,referenceNumber,TICKET_TYPE_DESCRIPTION,priority, currentStatus,convertedDate } = this.props;
const{troubleTicketDetails,workFlowDetails,followupDetails} =ticketDetailsInfo;
console.log("followupDetails" , followupDetails)
StepsVaue = workFlowDetails.currentNextActivity;
Steplabels = StepsVaue.map(StepsVaue => {
return StepsVaue._activityName;
});
SteplabelsTimes = StepsVaue.map(StepsVaue => {
return StepsVaue._maxHoldTime;
});
// SteplabelconcatValue = StepsVaue.map(StepsVaue => {
// return StepsVaue._activityName.concat("_",StepsVaue._maxHoldTime);
// });
currentStepPosition = StepsVaue.filter((item) => {
return item._activityStatus === "I"
});
const stepIndicatorStyles = {
stepIndicatorSize: 30,
currentStepIndicatorSize:40,
separatorStrokeWidth: 1,
currentStepStrokeWidth: 5,
stepStrokeCurrentColor: '#fe7013',
separatorFinishedColor: 'black',
separatorUnFinishedColor: 'black',
stepIndicatorFinishedColor: 'green',
stepIndicatorUnFinishedColor: '#aaaaaa',
stepIndicatorCurrentColor: '#ffffff',
stepIndicatorLabelFontSize: 0,
currentStepIndicatorLabelFontSize: 0,
stepIndicatorLabelCurrentColor: '#000000',
stepIndicatorLabelFinishedColor: '#ffffff',
stepIndicatorLabelUnFinishedColor: 'rgba(255,255,255,0.5)',
labelColor: 'black',
labelSize: 15,
currentStepLabelColor: 'black'
}
if(!_.isEmpty(referenceNumber) && (StepsVaue[0])) {
return (
<ImageBackground source={BG} style={styles.imgBG}>
<ScrollView>
<View style={styles.container}>
<View>
<Header title={title} subtitle={mobile} icon={icon} navigation={navigation}/>
</View>
<View style={styles.contentContainer}>
<View style={{ padding: 10 }}>
<View style={{marginBottom: 10}}>
<Card>
<CardItem header style={{backgroundColor: '#23476B', width: '100%', justifyContent: 'space-between'}}>
<View style={{flexDirection:'column'}}>
<View>
<RegularText text={`${TICKET_TYPE_DESCRIPTION} ID : ${referenceNumber}`} textColor='#fff' style={{ fontWeight: 'bold' }}/>
</View>
<View>
<SmallText text={`Raised ${convertedDate}`} textColor="#fff"/>
</View>
</View>
<View style={{flexDirection:'row'}}>
<View style={{flexDirection:'row'}}>
<IconNormal icon={this.iconSymbol(priority).symbol} type="AntDesign" style={{ color: this.iconSymbol(priority).color , paddingTop: 5}}/>
</View>
{/* <IconNormal icon={this.iconSymbol(priority).symbol} type="AntDesign" style={{ color: this.iconSymbol(priority).color , paddingTop: 5}}/> */}
<View style={{backgroundColor:'orange', borderRadius:50,height: 28, paddingRight: 10, paddingLeft: 10, paddingTop: 5}}>
<SmallText text={`${currentStatus}`} textColor='white'/>
</View>
</View>
</CardItem>
<CardItem>
<Body>
<View style={{flexDirection:'row', justifyContent: 'space-between', width: '100%'}}>
{/* <View style={{flexDirection:'column'}}>
<View>
<SmallText text="Catagory" textColor="grey"/>
</View>
<View>
<Text style={{ fontWeight: 'bold', fontSize:14 }}>{troubleTicketDetails.cat1}</Text>
</View>
</View> */}
{troubleTicketDetails.cat2.length > 0 &&
<View style={{flexDirection:'column'}}>
<View>
<SmallText text="Sub-Category" textColor="grey"/>
</View>
<View>
<Text style={{ fontWeight: 'bold', fontSize:14 }}>{troubleTicketDetails.cat2}</Text>
</View>
</View>}
{troubleTicketDetails.cat3.length > 0 &&
<View style={{flexDirection:'column'}}>
<View>
<SmallText text="Sub-SubCategory" textColor="grey"/>
</View>
<View>
<Text style={{ fontWeight: 'bold', fontSize:14 }}>{troubleTicketDetails.cat3}</Text>
</View>
</View>}
</View>
</Body>
</CardItem>
</Card>
</View>
<View>
<RegularText text={`WORKFLOW`} textColor='grey' style={{ fontWeight: 'bold', textAlign:'center', marginBottom:10 }}/>
</View>
<View style={{borderWidth:1, borderColor:'lightgrey', borderBottomColor:'white', padding:10, flexDirection:'column'}}>
<Card>
<CardItem>
<Body style={{justifyContent: 'center', alignItems: 'center'}}>
<View style={{flexDirection:'column'}}>
<RegularText text={` ${workFlowDetails.WRKFLW_DESC_V}`} textColor='green' style={{ fontWeight: 'bold' }}/>
</View>
<View style={{flexDirection:'column'}}>
<SmallText text={`Time Remaining is ${workFlowDetails.ESTIMATED_RESOLN_TM_N} Hours`} textColor='green' style={{ fontWeight: 'bold' }}/>
</View>
</Body>
</CardItem>
</Card>
</View>
<View style={{paddingLeft:10, height:300, marginBottom:10, borderWidth:1, borderColor:'lightgrey', borderTopColor:'white'}}>
<StepIndicator
customStyles={stepIndicatorStyles}
currentPosition={currentStepPosition.length}
stepCount={Steplabels.length}
labels={Steplabels}
renderLabel ={this.renderLabel()}
direction="vertical"
/>
</View>
<View>
<RegularText text={`NOTES`} textColor='grey' style={{ fontWeight: 'bold', textAlign:'center', marginBottom:10 }}/>
</View>
<View style={{marginLeft:10,marginRight:10}}>
{Array.isArray(followupDetails) && followupDetails.map(
({ INCIDENTINITIATOR, INCIDENTTIMESTAMP,NOTES, USERGROUPNAME}, index) => {
var INCIDENTINITIATOR_Value;
if(INCIDENTINITIATOR =="U"){
INCIDENTINITIATOR_Value ="USER";
}
else{
INCIDENTINITIATOR_Value ="CUSTOMER";
}
<View style={{marginBottom: 10}} key={index}>
<Card>
<CardItem header style={{backgroundColor: '#fff', justifyContent: 'space-between', borderBottomColor: '#f1f1f1', borderBottomWidth: 1}}>
<View style={{flexDirection:'column'}}>
<View style={{backgroundColor:'lightgrey', borderRadius:50,height: 28, paddingRight: 10, paddingLeft: 10, paddingTop: 5}}>
<SmallText text={`${INCIDENTINITIATOR_Value}`} textColor='grey'/>
</View>
<View>
<Text style={{ fontSize:14 }}> {NOTES} </Text>
</View>
</View>
</CardItem>
<CardItem>
<Body>
<View style={{flexDirection:'row', justifyContent: 'space-between', width: '100%'}}>
<View>
<SmallText text={`${USERGROUPNAME}`} textColor="grey"/>
</View>
<View>
<SmallText text={`${INCIDENTTIMESTAMP}`} textColor="grey"/>
</View>
</View>
</Body>
</CardItem>
</Card>
</View>
})
}
</View>}
{/* <Button block bordered dark>
<Text>Add a Note</Text>
</Button> */}
</View>
</View>
</View>
</ScrollView>
</ImageBackground>
);
}else{
return(
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
<LoadingSpinner color="#00678F"/>
</View>
)
}
}
}
/*<IconNormal icon={this.iconSymbol(priority).symbol} type="AntDesign" style={{ color: this.iconSymbol(priority).color , paddingTop: 5}}/> */
export default TroubleTicketDetails;
Thanks

Related

How to like individual image specific to each user. Through expo/react native/firebase

My main issue with my current react native app is that when a user searches for a nft using a web3 api im using, i render a like button next to every image of the nft. I added some logic for making the like button red but when i like a NFT all the other like buttons for all the other NFT's get liked. How can i fix this to where only the specific like button that gets pressed shows that it is pressed.
code:
export const Profile = ({setLoggedIn}) => {
const [profileData, setProfileData] = useState([]);
const [apiQ,setApiQ] = useState("")
const [nfttei,setNftTei] = useState("")
const [comments,setComments] = useState([])
const[commentText,setCommentText] = useState("")
async function getData () {
const options = {method: 'GET', headers: {accept: 'application/json', 'X-API-Key': 'WYON0dXwg4zG3GSsaPb79ofaPTLAbDUpmt01OuTlZihmzoH1F059it3bdsXSou0t'}};
const data = await fetch(`https://deep-index.moralis.io/api/v2/nft/search?chain=eth&format=decimal&q=${apiQ}&filter=name&limit=10`, options)
const ddata = await data.json()
setProfileData(ddata.result)
}
async function handleNftIn () {
setApiQ(nfttei)
setNftTei("")
}
useEffect(() => {
getData();
}, [apiQ]);
function liked (id) {
setPressed(true)
}
const [pressed,setPressed] = useState(false)
return (
<View style={{padding: 20}}>
<Text style={{fontSize: 40, fontWeight: "700"}}>NFTS</Text>
<View style={{marginBottom: 20}}>
<Text style={{fontSize: 25, fontWeight: "650", marginBottom: 10}}>What kind of NFT?</Text>
<View style={{flexDirection: "row", justifyContent: "space-between", alignItems: "center"}}>
<TextInput
placeholder='type nft keyword'
style={{
backgroundColor: "#D1D1D1",
borderRadius: 20,
padding: 10,
fontSize: 16,
width: "60%"
}}
onChangeText={(val) => setNftTei(val)}
value={nfttei}
/>
<AntDesign name="rightcircle" size={30} color="#3A84EC" onPress={handleNftIn}/>
</View>
</View>
<ScrollView>
{profileData ? <>
{profileData.map((el, key,id) =>
<View style={{
backgroundColor: "#fff",
padding: 10,
borderRadius: 20,
marginBottom: 20
}} key={key}>
<View style={{position: "relative"}}>
<View style={{position: "absolute", zIndex: 10, right: 0, backgroundColor: "#fff", padding: 8,borderRadius: 30, marginRight: 20, marginTop: 10}}>
<AntDesign onPress={(id) => liked(id)} name="heart" size={24} color={pressed ? "#FF717B": "grey"} />
</View>
{JSON.parse(el.metadata).image.includes("https") ? <>
<Image source={{
uri: `${JSON.parse(el.metadata).image}`
}} style={{width: "1005", height: 200, borderRadius: 30, width: "100%"}}/>
</>: null}
</View>
<View style={{marginTop: 20}}>
<View style={{flexDirection: "row", alignItems:"center"}}>
<Text style={{marginRight:10, color: "grey"}}>ID</Text>
<View style={{width: 10,height:10,backgroundColor:"#000", borderRadius:50}}></View>
<Text style={{marginLeft: 10}}>{el.token_id}</Text>
</View>
<Text style={{fontSize: 20, fontWeight: "700", marginBottom: 10}} key={key}>{JSON.parse(el.metadata).name}</Text>
<Text>{JSON.parse(el.metadata).description}</Text>
<View style={{backgroundColor: "#000", borderRadius: 10,padding:7,justifyContent: "center", alignItems: "center"}}>
{el.token_uri.includes("https") ? <>
<A style={{color:"white", fontSize: 19}} href={el.token_uri}><Text>learn More</Text></A>
</> : <Text>Learn More</Text>}
</View>
</View>
</View>
)}
</>: <>
<Text style={{
fontWeight:"700",
color:"#000",
fontSize:20,
marginBottom:20
}}>Try searching something! Anything!</Text>
<Image source={{
uri:"https://mir-s3-cdn-cf.behance.net/project_modules/max_1200/50e513115094373.6047d1f4cf3f1.jpg"
}} style={{
width:"100%",
borderRadius:20,
height:500
}}/>
</>}
</ScrollView>
</View>
)
}
image:
what its giving me:

React-Native FlatList is not scrolling

I am quite new to react native. I have created a FlatList for rendering this list of items, however, it is not scrolling. I've googled it for hours and tried nearly everything suggested in stack overflow threads - removed flex, added flex, wrapped it in a view, but nothing seems to work.
Here is my code (the issue is in the second FlatList) -
return(
<View style = {{ height: '100%' }}>
<View style = {{ width: '100%' }}>
<AppHeader />
</View>
<View style = {{ width: '100%'}}>
<View style = {{ width: '70%', alignSelf: 'center', flex: 1 }}>
<View>
<FlatList
data = {this.getTodayDay()}
renderItem = {this.renderItemDays}
keyExtractor = {this.keyExtractor}
/>
</View>
<FlatList
data = {this.getVisibleHours()}
renderItem = {this.renderItem}
keyExtractor = {this.keyExtractor}
scrollEnabled = {true}
/>
</View>
</View>
</View>
this.renderItem -
renderItem = () => {
// irrelevant code
if( isClass === true ){
return(
<ListItem bottomDivider = {true} style = {styles.renderItemActiveClass}>
<ListItem.Content>
<TouchableOpacity
onPress = {()=>{
this.props.navigation.navigate('ClassDetailsScreen', { "data": classData })
}}>
<ListItem.Title>{ definiteClassTime }</ListItem.Title>
<ListItem.Subtitle>{ classData.class_name }</ListItem.Subtitle>
</TouchableOpacity>
</ListItem.Content>
</ListItem>
)
}
else{
return(
<ListItem bottomDivider = {true} style = {styles.renderItemClass}
containerStyle = {styles.renderItemContent}>
<ListItem.Content>
<ListItem.Title>{item}:00</ListItem.Title>
<ListItem.Subtitle>No Class</ListItem.Subtitle>
</ListItem.Content>
</ListItem>
)
}
}
the StyleSheet -
renderItemClass: {
borderColor: 'purple',
borderWidth: 2
},
renderItemActiveClass: {
borderColor: 'green',
borderWidth: 2
},
renderItemContent: {
},
Could somebody please tell me what I'm doing wrong?
Add a height to both the flatlist. And also wrap your second flatlist within a seperate view. Here is an example:
return (
<View style={{ height: "100%" }}>
<View style={{ width: "100%" }}>
<AppHeader />
</View>
<View style={{ width: "100%" }}>
<View style={{ width: "70%", alignSelf: "center", flex: 1 }}>
<View style={{ height: 60, alignSelf: "center" }}>
<FlatList
data={this.getTodayDay()}
renderItem={this.renderItemDays}
keyExtractor={this.keyExtractor}
/>
</View>
<View style={{ height: 60, alignSelf: "center" }}>
<FlatList
data={this.getVisibleHours()}
renderItem={this.renderItem}
keyExtractor={this.keyExtractor}
scrollEnabled={true}
/>
</View>
</View>
</View>
</View>
);

How to pass Flatlist items to another screens Flatlist?

How do I pass FlatList items to another screen that also have a FlatList?
I'm using React Navigation V5 to pass the FlatList item to the other screen. Thats working fine. I can see the text when only using ´<Text.>{details.id}</Text .>´ but not when trying to pass it to FlatList, then there is nothing.
CODE
import React, { useState } from 'react';
import {
View,
TextInput,
FlatList,
Text,
TouchableOpacity,
Linking,
Modal,
ScrollView,
} from 'react-native';
import { useTheme } from '../Data/ThemeContext';
import DataBase from '../Data/DataBase';
import Octicons from 'react-native-vector-icons/Octicons';
export default function Home({ navigation }) {
const [search, setSearch] = useState('');
const [masterDataSource, setMasterDataSource] = useState(DataBase);
const [modalVisible, setModalVisible] = useState(false);
const [details, setDetails] = useState('');
const { colors } = useTheme();
const filteredDataSource = masterDataSource.filter((item) => {
return (
item.name.includes(search) ||
(item.id && item.id.includes(search)) ||
(item.gluten && item.gluten.includes(search)) ||
(item.company && item.company.includes(search))
);
});
const itemSeparatorComponent = () => {
return (
<View
style={{
margin: 3,
}}></View>
);
};
const emptyComponent = () => {
return (
<View style={{ alignItems: 'center' }}>
<Text style={{ color: colors.text }}>Finns inte produkten med?</Text>
<View style={{ marginTop: 30 }}>
<TouchableOpacity
onPress={() => Linking.openURL('')}>
<Text
style={{
color: colors.text,
borderWidth: 1,
borderColor: colors.text,
padding: 10,
borderRadius: 5,
backgroundColor: colors.card,
}}>
KONTAKTA OSS
</Text>
</TouchableOpacity>
</View>
</View>
);
};
const renderItem = ({ item }) => {
return (
<View>
<TouchableOpacity
style={{
marginLeft: 20,
marginRight: 20,
elevation: 3,
backgroundColor: colors.card,
borderRadius: 10,
}}
onPress={() => {
setModalVisible(true);
setDetails(item);
}}>
<View style={{ margin: 10 }}>
<Text style={{ color: colors.text }}>{item.company}</Text>
<Text style={{ color: colors.text, fontWeight: '700' }}>
{item.name}
</Text>
<Text style={{ color: colors.text }}>{item.gluten}</Text>
<Text style={{ color: colors.text }}>{item.id}</Text>
</View>
</TouchableOpacity>
</View>
);
};
return (
<View style={{ flex: 1, backgroundColor: colors.background }}>
<Modal
animationType="none"
hardwareAccelerated={true}
transparent={true}
visible={modalVisible}
onRequestClose={() => {
setModalVisible(!modalVisible);
}}>
<View
style={{
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: 'rgba(0,0,0,0.8)',
}}>
<View
style={{
backgroundColor: colors.Modal,
padding: 35,
borderRadius: 10,
width: '80%',
height: '80%',
}}>
<ScrollView showsVerticalScrollIndicator={false}>
<View style={{ marginTop: 20 }}>
<Text style={{ color: colors.text }}>{details.company}</Text>
<Text
style={{ color: colors.text, marginTop: 20, fontSize: 20 }}>
{details.name}
</Text>
<Text style={{ color: colors.text, marginTop: 20 }}>
{details.gluten}
</Text>
<Text style={{ color: colors.text, marginTop: 20 }}>
Ingredienser
</Text>
<Text style={{ color: colors.text, marginTop: 2 }}>
{details.ingredients}
</Text>
<Text style={{ color: colors.text, marginTop: 30 }}>
{details.id}
</Text>
</View>
</ScrollView>
<View
style={{
borderTopWidth: 1,
borderTopColor: colors.text,
marginBottom: 10,
}}></View>
<View
style={{ flexDirection: 'row', justifyContent: 'space-evenly' }}>
<TouchableOpacity
onPress={() => {
const updated = [...masterDataSource];
updated.find(
(item) => item.id === details.id,
).selected = true;
setMasterDataSource(updated);
navigation.navigate('Inköpslista', {
items: updated.filter((item) => item.selected),
});
}}>
<Text>Lägg i Inköpslistan</Text>
</TouchableOpacity>
<TouchableOpacity
onPress={() => {
setModalVisible(false);
}}>
<Text style={{ alignSelf: 'center', color: '#FF0000' }}>
Stäng
</Text>
</TouchableOpacity>
</View>
</View>
</View>
</Modal>
<View
style={{
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'center',
padding: 20,
backgroundColor: colors.Textinput,
elevation: 12,
}}>
<TextInput
style={{
flex: 1,
backgroundColor: '#fff',
borderTopLeftRadius: 5,
borderBottomLeftRadius: 5,
}}
placeholder=" SÖK PRODUKT NAMN / STRECKKOD"
placeholderTextColor="#000"
onChangeText={(text) => setSearch(text)}
value={search}
autoCapitalize="words"
/>
<Octicons
style={{
marginLeft: 1,
padding: 13,
backgroundColor: '#fff',
height: 49,
borderTopRightRadius: 5,
borderBottomRightRadius: 5,
}}
name="checklist"
size={25}
color="#000"
onPress={() =>
navigation.navigate('Inköpslista', {
items: masterDataSource.filter((item) => item.selected),
})
}
/>
</View>
<View style={{ flex: 1, marginTop: 20 }}>
<FlatList
data={filteredDataSource}
ItemSeparatorComponent={itemSeparatorComponent}
keyExtractor={(_, index) => index.toString()}
renderItem={renderItem}
initialNumToRender={4}
maxToRenderPerBatch={5}
windowSize={10}
removeClippedSubviews={true}
updateCellsBatchingPeriod={100}
showsVerticalScrollIndicator={true}
ListEmptyComponent={emptyComponent}
contentContainerStyle={{ paddingBottom: 20 }}
/>
</View>
</View>
);
}
SECOND SCREEN
import React from 'react';
import { View, Text, FlatList, Button } from 'react-native';
export default function ShoppingList({ route, navigation }) {
const RenderItem = ({ item }) => {
return (
<TouchableOpacity
style={{ marginHorizontal: 10, marginVertical: 15 }}
onPress={() => {}}>
<Text>{item.id}</Text>
<Text>{item.name}</Text>
</TouchableOpacity>
);
};
return (
<View
style={{
flex: 1,
alignItems: 'center',
justifyContent: 'center',
marginTop: 30,
}}>
<Button title="Go back" onPress={() => navigation.goBack()} />
<FlatList
data={route.params && route.params.items}
renderItem={RenderItem}
/>
</View>
);
}
Based on your question, this is the flow that you want
User has flat list with a set of items
When an item is clicked a modal is opened
If the user wants he clicks 'Add to cart' which will add item to cart and open cart.
When cart is opened user is shown a flatlist with the selected items.
Screen 1 : Home
Here you already have a modal but you pass a single item instead of an array.
So the better way is to use the masterDataSource state that you have and add a 'selected' property to it.
So the button in the Modal would be like this
<Button
title="Add and View Cart"
onPress={() => {
const updated = [...masterDataSource];
updated.find((item) => item.id === details.id).selected = true;
setMasterDataSource(updated);
navigation.navigate('Cart', {
items: updated.filter((item) => item.selected),
});
}}
/>
Once you click the Button you would be taken to the cart page with the items array which you have selected (This will have the previous items as well).
The Cart screen will have a Flatlist to show the items that are passed via params like below. RenderItem can be the code for your item.
<FlatList
data={route.params && route.params.items}
renderItem={RenderItem}
/>
You can run the sample below
https://snack.expo.io/#guruparan/cartexample
(Modal doesnt work properly on web you can try the android version)
According to React Native Docs, the prop data on FlatList should contain an Array, like this [{...}] or this [{...},{...},{...}...]. But you are trying to pass an Object to the FlatList on the ShoppingList screen, like this {...}.
On ShoppingList Screen when you're destructuring like the following
const { details } = route.params;
You are creating an object, which looks like this {...}
So you need to convert it to an array. Use the following code snippet
const itemInfo = []
itemInfo.push(details)
Now just pass itemInfo to data prop of FlatList.
Your ShoppingList screen should look like this.
import React from 'react';
import {
View,
FlatList,
Text,
} from 'react-native';
export default function ShoppingList({ route }) {
const { details } = route.params;
const itemInfo = [];
itemInfo.push(details);
return (
<View style={{ flex: 1, backgroundColor: "white" }}>
<FlatList
data={itemInfo}
keyExtractor={(item) => item.id.toString()}
renderItem={({ item }) => (
<View>
<Text style={{ color: "black" }}>{item.company}</Text>
<Text style={{ color: "black" }}>{item.name}</Text>
<Text style={{ color: "black" }}>{item.gluten}</Text>
<Text style={{ color: "black" }}>{item.id}</Text>
</View>
)}
/>
</View>
);
}

Fetch data from API using flatlist in React Native

I'm trying to display data for a specific ID. Since my data is an array. I used flatlist to display it. It displays the data but it's displaying all ID. How I can solve this issue. Anyone can help with this?
<View style={[components.container]} >
<View style={[components.logTopPanel, { backgroundColor: '#48bbae' }]} >
<View style={components.back_container}>
</View>
<View style={[components.logTitleContainer]} >
<TouchableOpacity style={components.icon_container} onPress={() => this.props.navigation.navigate('LeaveIndexScreen')}>
<View style={[components.back_button, components.justifyCenter, components.alignCenter, { marginHorizontal: 15 }]} >
<MaterialIcon name="arrow-back" size={28} color="white" />
</View>
</TouchableOpacity>
<View style={components.title_container}>
<Text style={[components.headerTextTitle, { textAlign: 'center' }]}>Leave Application</Text>
<Text style={[components.headerText]}> Records Details</Text>
</View>
</View>
</View>
<View style={[components.alignCenter, components.boxWithShadow, colours.backWhite, { borderBottomLeftRadius: 10,borderBottomRightRadius: 10,marginBottom: 5 }]}>
<View style={components.textFlexStart}>
<Text style={[components.titleTextStyle],{width:'100%', fontSize:20,textAlign:'center'}}>{staticData.get_centre_settings().centre.centre_name}</Text>
</View>
</View>
<View style={[components.logDetailPanel, components.alignCenter, { paddingHorizontal: '3%', backgroundColor: '#FBF2F0' }]} >
<ScrollView contentContainerStyle={[{ flexDirection: 'row', marginTop: 5 }]} >
{this.state.view_access == false
? <NoAccessScreen></NoAccessScreen>
: this.state.isLoading
? <View style={[components.alignCenter, components.justifyCenter, components.pad_10]} >
<ActivityIndicator />
</View>
: <FlatList
data={this.state.staffLeave}
renderItem={({ item }) =>
this.state.text == null || item.staff_name.toUpperCase()().includes(this.state.text.toUpperCase()())
? <TouchableOpacity>
<View style={[components.listContainer]}  >
<View style={components.cardContainer}>
<View style={[components.dotContainer]} >
<View style={[components.flex_row, components.justifyAlignStart, { padding: 5 }]}>
<View style={{ width: '75%' }}>
{
item.staff_name != null
?
<View style={{ width: '100%' }}>
<Text style={[components.titleTextStyle]}>{item.name}</Text>
</View>
: null
}
{
item.centre_name != null
?
<View style={{ width: '100%' }}>
<Text style={[components.titleTextStyle]}>{item.centre_name}</Text>
</View>
: null
}
{
item.leave_days != null
?
<View style={{ width: '100%' }}>
<Text style={[components.titleTextStyle]}>{item.leave_days}</Text>
</View>
: null
}
{
item.date_range != null
?
<View style={{ width: '100%' }}>
<Text style={[components.titleTextStyle]}>{item.date_range}</Text>
</View>
: null
}
{
item.approved_by != null
?
<View style={{ width: '100%' }}>
<Text style={[components.titleTextStyle]}>{item.approved_by}</Text>
</View>
: null
}
{
item.approved_date != null
?
<View style={{ width: '100%' }}>
<Text style={[components.titleTextStyle]}>{item.approved_date}</Text>
</View>
: null
}
{
item.status != null
?
<View style={{ width: '100%' }}>
<Text style={[components.titleTextStyle]}>{item.status}</Text>
</View>
: null
}
</View>
</View>
</View>
</View>
</View>
</TouchableOpacity>
: null
}
keyExtractor={(item, index) => index.toString()}
extraData={this.state}
nestedScrollEnabled={true}
/>
}
</ScrollView>
<ActionButton
buttonColor={Colors.blueSky}
offsetX={20}
onPress={() => navigate('LeaveEditScreen', { id: this.state.staff_id })}
renderIcon={() => { return (<MaterialIcon name="edit" size={20} color="white" />); }}
/>
</View>
</View>
);
}
This was the output.
I kept searching for this but couldn't find an answer that will make this clear.
Thanks!

React Native Register Button issue

In the React Native application, the button continues to operate when the information is entered incorrectly on the member entry and registration page. The button is not activated again to re-enter information. Could you help?
In other words, when the information is entered incorrectly or missing, the registration button is rotating continuously.
Please review the screenshot and codes.
Screenshot:
[![Screen shot with the UI][1]][1]
My codes are:
import React from 'react';
import { StyleSheet, Text, View, Image, Dimensions, TextInput, TouchableOpacity, ActivityIndicator } from 'react-native';
import LinearGradient from 'react-native-linear-gradient';
import Icon from 'react-native-vector-icons/Ionicons';
const { height, width } = Dimensions.get('window');
const LogoImg = require('../assets/img/challengelogo.png');
import { KeyboardAwareScrollView } from 'react-native-keyboard-aware-scrollview'
import {connect} from 'react-redux';
import * as appActions from './actions';
export class signupView extends React.Component {
constructor(props){
super(props);
this.state = {
checkboxChecked: false,
checkboxIcon: 'ios-square-outline'
}
}
render() {
const { container, innerContainer, innerImageContainer, buttonView , buttonViewRegister, innerButtonTextView, innerButtonView, termsView} = styles;
return (
<LinearGradient
colors={['#f9a149', '#e86e52', '#d6375c']}
style={ container }>
<KeyboardAwareScrollView
showsVerticalScrollIndicator={false}
keyboardShouldPersistTaps="always"
style={styles.scrollContainer}>
<View style={innerContainer}>
<Image
source={LogoImg}
style={{ width: width*0.45, height: width*0.55 }}
resizeMode={'contain'}
/>
<View style={{flexDirection:'row', alignItems:'center'}}>
<Text style={{color:'#fff', fontSize:18, margin:10, textDecorationLine:'underline'}} >KAYIT OL</Text>
</View>
<View style={styles.searchSection}>
<Icon style={styles.searchIcon} name="ios-person-add" size={30} color="#000"/>
<TextInput
style={styles.input}
placeholder="Kullanıcı Adı"
underlineColorAndroid="transparent"
autoCapitalize = 'none'
autoCorrect = {false}
value = {this.props.r_name}
onChangeText={this._onNameChanged.bind(this)}
autoFocus = { true }
blurOnSubmit = { false }
returnKeyType = { "next" }
onSubmitEditing = {() => {this.mailTextInput.focus()} }
/>
</View>
<View style={styles.searchSection}>
<Icon style={styles.searchIcon} name="ios-mail-outline" size={30} color="#000"/>
<TextInput
ref={(input) => { this.mailTextInput = input; }}
style={styles.input}
placeholder="Mail Adresi"
underlineColorAndroid="transparent"
keyboardType="email-address"
autoCapitalize = 'none'
autoCorrect = {false}
value = {this.props.r_email}
onChangeText={this._onEmailChanged.bind(this)}
blurOnSubmit = { false }
returnKeyType = { "next" }
onSubmitEditing = {() => {this.passwordTextInput.focus()} }
/>
</View>
<View style={styles.searchSection}>
<Icon style={styles.searchIcon} name="md-lock" size={30} color="#000"/>
<TextInput
ref={(input) => { this.passwordTextInput = input; }}
style={styles.input}
placeholder="Şifre"
onChangeText={(searchString) => {this.setState({searchString})}}
underlineColorAndroid="transparent"
secureTextEntry={true}
autoCapitalize = 'none'
autoCorrect = {false}
value = {this.props.r_password}
onChangeText={this._onPasswordChanged.bind(this)}
/>
</View>
{ !this.props.isloadingSignup &&
<TouchableOpacity onPress={this._onSignUpPress}>
<View style={ [buttonView, buttonViewRegister]}>
<View style={innerButtonView}>
<Icon name="ios-person-add" size={30} color="#000" />
</View>
<View style={innerButtonTextView}>
<Text style={{ color:'#FFF', fontSize: 15}}>Kayıt Ol</Text>
</View>
</View>
</TouchableOpacity>
||
<TouchableOpacity>
<View style={ [buttonView, buttonViewRegister]}>
<View style={innerButtonView}>
<Icon name="ios-person-add" size={30} color="#000" />
</View>
<View style={innerButtonTextView}>
<ActivityIndicator color="white" size='small' />
</View>
</View>
</TouchableOpacity>
}
<TouchableOpacity onPress={this._onPressTerms}>
<View style={ [termsView]}>
<Icon name={this.state.checkboxChecked ? 'ios-checkbox': 'ios-square-outline'} size={30} color="#000" />
<Text style={{ color:'#FFF', fontSize: 15, marginLeft: 10}}><Text onPress={this._onPressTermsConditions } style={{ textDecorationLine: "underline"}}> Kullanım koşullarını</Text> Kabul Ediyorum.</Text>
</View>
</TouchableOpacity>
</View>
</KeyboardAwareScrollView>
</LinearGradient>
);
}
_onSignUpPress = () => {
if(this.state.checkboxChecked) {
var registerBody = {
email: this.props.r_email,
password: this.props.r_password,
password_confirmation: this.props.r_password,
name: this.props.r_name
};
this.props.dispatch(appActions.register(registerBody));
} else {
alert("Lütfen önce Kullanıcı şartlarını kabul edin.");
}
}
_onEmailChanged = (email) => {
this.props.dispatch(appActions.emailChanged(email));
}
_onNameChanged = (name) => {
this.props.dispatch(appActions.nameChanged(name));
}
_onPasswordChanged = (password) => {
this.props.dispatch(appActions.passwordChanged(password));
}
_onPressTerms = () => {
this.setState({ checkboxChecked: !this.state.checkboxChecked })
}
_onPressTermsConditions = () => {
this.props.navigator.push({
screen: 'challenge.TermsOfUse',
navigatorStyle: {
navBarHidden: true
}
});
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'flex-start',
},
scrollContainer:{
flex: 1,
},
innerContainer:{
flexDirection:'column',
alignItems:'center',
marginTop: height*0.08,
},
searchSection: {
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#fff',
width:width*0.7,
marginTop:7
},
searchIcon: {
paddingTop:5,
paddingBottom:5,
paddingLeft:10,
paddingRight:10
},
input: {
flex: 1,
backgroundColor: '#fff',
color: '#424242',
justifyContent:'center',
},
buttonView:{
width: width*0.7,
marginTop:20,
flexDirection:'row',
},
buttonViewRegister:{
backgroundColor:"#2b74a7"
},
innerButtonView:{
backgroundColor:'#bab9b9',
width:45,
height:42,
justifyContent:'center',
alignItems:'center'
},
innerButtonTextView:{
flex:1,
justifyContent:'center',
alignItems:'center'
},
termsView:{
width: width*0.8,
marginTop:20,
flexDirection:'row',
justifyContent:'center',
alignItems:'center'
}
});
const mapStateToProps = ({ signup }) => {
return { r_email, r_password, r_name, isloadingSignup } = signup;
};
export default connect(mapStateToProps)(signupView);
Firstly, thanks for your response. I couldn't put the codes here because it crossed the character limit. So you can review the action content from this link. http://karahankaraman.com/actions/index.js
I think you are overcomplicating your signup page. Do you really need to dispatch to redux to handle your signup logic? You might need to show us your actions.js file if this continues.
Meanwhile do this:
{ !this.props.isloadingSignup ?
<TouchableOpacity onPress={this._onSignUpPress}>
<View style={ [buttonView, buttonViewRegister]}>
<View style={innerButtonView}>
<Icon name="ios-person-add" size={30} color="#000" />
</View>
<View style={innerButtonTextView}>
<Text style={{ color:'#FFF', fontSize: 15}}>Kayıt Ol</Text>
</View>
</View>
</TouchableOpacity>
:
<View style={ [buttonView, buttonViewRegister]}>
<View style={innerButtonView}>
<Icon name="ios-person-add" size={30} color="#000" />
</View>
<View style={innerButtonTextView}>
<ActivityIndicator color="white" size='small' />
</View>
</View>
}

Categories