Type error : cannot read property from mapstatetoprops - react-native

I am new to react-native
In reducer I set the initial value of the state.
while receiving the value in mapstate to props, it gives me the error
Type error : cannot read property of datasource.
I tried to set initial state to blank object then on fetch I set the value but I am still getting the error.
/* This is Dashboard.js */
import React, { Component } from 'react'
import { FlatList, StyleSheet, View, Text,Image,ActivityIndicator,
Picker,TouchableOpacity,SectionList,DrawerLayoutAndroid,Alert,
TouchableHighlight,Button} from 'react-native'
import NumericInput from 'react-native-numeric-input'
import {connect} from 'react-redux';
import {
createDrawerNavigator,
createStackNavigator,
createAppContainer,
} from 'react-navigation';
const mapStateToProps = (state) =>{
console.log(state)
return {
datasource:state.datasource,
isLoading:state.isLoading,
switchValue: state.switchValue,
page:state.page,
rerender:state.rerender,
isFetching: state.isFetching,
search:state.search,
LastSelectedItem:state.LastSelectedItem,
ItemSelected:state.ItemSelected,
setdrawerstate:state.setdrawerstate
}
};
const mapDispatchToProps=(dispatch)=>{
console.log('i am ni map dispatch to props')
return {
quantitychange:(prodindex, changevalue)=>dispatch({type:"CHANGE_QTY",
index:prodindex,
value:changevalue}),
selectvaluechange:(index,itemvalue,itemindex)=>dispatch({type:"CHANGE_WEIGHT",
index:index,
itemvalue:itemvalue,
itemindex:itemindex}),
ToogleDrawerState:(newState)=>dispatch({type:'TOOGLE_DRAWER',newState:newState}),
taggleSwitch:(value,ind)=>dispatch({type:'TOOGLE_SWITCH',value:value,ind:ind}),
fetchAllData:(AlldataJson)=>dispatch({type:'ALL_DATA',AlldataJson:AlldataJson})
};
};
class DashBoard extends Component {
constructor(props) {
super(props)
console.log('i am in constructor')
console.log('the value getting as props is '+JSON.stringify(props));
// this.selectvaluechange=this.selectvaluechange.bind(this);
// this._opendrawer = this._opendrawer.bind(this);
} //constructor
packageList = (index) =>{
// console.log('i am in package list'+index)
return( this.props.datasource[index].pack.map( (x,j) => {
return( <Picker.Item label={x.Weight} key={j} value={x.packId}/>)}));
}
// Verdana 20
renderItem = ({ item,index }) => {
// console.log('i am in render item index is '+index+' item vale is '+JSON.stringify(item));
return(
<View style={{
flex: 1, flexDirection: 'row', marginBottom: 3,
paddingBottom: 10, paddingTop:10, paddingLeft: 10, backgroundColor: 'white', height: '25%'
}}>
<View style={{ width: '30%' }}>
<Image style={{ resizeMode: 'contain', height: '100%',width:'100%' }}
source={{ uri: this.props.datasource[index].imageUrl }} />
</View>
<View style={{ alignContent: 'center', paddingLeft: 40, width: '65%' }}>
<Text style={{
fontSize: 20, color: 'black', fontWeight: 'bold',
fontFamily: 'Verdana'
}}>
{item.Heading}</Text>
<Text style={{
fontSize: 12, paddingTop: 10, fontFamily: 'Verdana',
color: 'black', fontWeight: 'bold'
}}>{item.Details}</Text>
<View style={{ flex: 1, flexDirection: 'row', paddingTop: 15 }}>
<Text style={{ width: 40, height: 30, fontFamily: 'Verdana', fontWeight: 'bold' }}>Qty :</Text>
<NumericInput
totalHeight={30}
totalWidth={80}
minValue={0}
value={this.props.datasource[index].Qty}
onChange={(value) => this.props.quantitychange(index, value)} />
<Picker
style={{ marginLeft: 10, width: '45%', height: 40, fontFamily: 'Verdana', fontWeight: 'bold' }}
mode="dropdown"
selectedValue={this.props.datasource[index].packselectedValue}
onValueChange={(itemValue, itemIndex) => this.props.selectvaluechange(index, itemValue, itemIndex)}>
{this.packageList(index)}
</Picker>
</View>
<View >
<Text style={{ fontFamily: 'Verdana', fontWeight: 'bold' }}>Price : {this.props.datasource[index].
pack[this.props.datasource[index].packselectedValue].Price}
<Text style={{ fontFamily: 'Verdana', fontWeight: 'bold' }}> Amount : {this.props.datasource[index].
pack[this.pack.datasource[index].packselectedValue].Price *
this.props.datasource[index].Qty}
</Text>
</Text>
</View>
</View>
</View>
)
}
renderSeperator=()=>{
console.log('I am renderseperator the data ')
return(
<View style={{height:1,width:'100%',backgroundColor:'black'}}/>
)
}
onRefresh=()=>{
console.log('I am refreshing the data '+this.props)
// this.setState({isFetching:false})
}
componentDidMount() {
AlldataJson = [{}];
console.log('i am in component didmount ');
const url='./../Data/AllProduct.json'
// ./../Data/AllProduct.json'
fetch(url)
.then((response) => response.json())
.then((responsejson => {
console.log('i am in response json')
fetchAllData(responsejson)}))
//this.setState({ datasource: responsejson })})
.catch((error) => {
console.log('error in fetching the data bhasker')
this.props.fetchAllData(AlldataJson);
console.log('i am after fetchalldata function'+this.props)
})
this.props.navigation.setParams({ opendrawer: this._opendrawer});
}
// data={this.state.page===1?this.state.datasource:[this.state.datasource]}
render() {
return (
this.props.isLoading ?
<View style={{ flex: 1, justifyContent: 'center', alignContent: 'center' }}>
<ActivityIndicator size='large' color='#330066' animating />
</View> : <View>
{/* <Text>{this.props.datasource[0].Heading}</Text> */}
<FlatList
extraData={this.props.state}
data={this.props.datasource}
onRefresh={() => this.onRefresh()}
refreshing={this.props.isFetching}
renderItem={(item,index)=>this.renderItem(item,index)}
keyExtractor={(item, index) => {
console.log('i am in keyextractor')
return (item.Id)}}
ItemSeparatorComponent={this.renderSeperator}/>
</View>
)
}
}
export default connect(mapStateToProps,mapDispatchToProps)(DashBoard);
/* My Reducer code is */
import * as types from '../Action/ActionType'
import { objectExpression } from '#babel/types';
import Allproduct from './../Data/AllProduct';
const initialstate={
datasource: Allproduct,
isLoading:false,
switchValue: true,
page:1,
rerender:true ,
isFetching: false,
search:"" ,
LastSelectedItem:{Item:"",qty:"",weight:""},
ItemSelected:0,
setdrawerstate:true
}
const reducer = (state = initialstate, action) => {
console.log('i am in reducer '+JSON.stringify(action));
switch (action.type) {
case "CHANGE_QTY":
break;
case "CHANGE_WEIGHT":
break;
case "TOOGLE_DRAWER":
break;
case "TOOGLE_SWITCH":
break;
case "ALL_DATA":
console.log('i am in all data') ;
return state;
default:
return state;
}
}
export default reducer;
/* if i comment datasource in mapstatetoprops it print the text value.
Allproduct json is below
*/
[{"Id":"1","Heading":"Ashirvad","Details": "ashirvad Atta - Whole Wheet 10k Pouch","imageUrl": "https://www.aashirvaad.com/images/packet-2-right.png", "Qty": 0,"pack": [{"packId":0,"Weight": "1kg","Price": 25}, {"packId":1,"Weight": "2kg","Price": 50}, {"packId":2,"Weight": "5kg","Price": 125}, {"packId":3,"Weight": "10kg","Price": 250}], "packselectedValue":0,"isselected": false,"categoryID":"1"}, {"Id":"2","Heading": "Tata Salt","Details": "Tata Salt Iodised Salt 1kg Product","imageUrl": "http://tatasalt.com/public/front_assets/images/tab-product-img1.png","Qty": 0,"pack": [{"packId":0,"Weight": "1kg","Price": 9.5},{"packId":1,"Weight": "2kg","Price": 19}, {"packId":2,"Weight": "5kg","Price": 47 },{"packId":3,"Weight": "10kg","Price": 92}],"packselectedValue":0,"isselected": false,"categoryID":"1"},

Related

When I call an API on My First Page I want to fire Second Page API at the same time how can I achieve it! | React Native

I am working on react native from 3 months means I am still a beginner ,Help me with this Functionality : What I want is that when I add a product to my shopping cart the cart number on my bottom tab should increase at the same time . How can I achieve it?
This is my add to cart screen Here I am adding my products to the cart
import {
View, Text, StyleSheet, ScrollView, TouchableOpacity, Alert, Image, ActivityIndicator, Dimensions
} from 'react-native'
import React, { useEffect, useState } from 'react'
import Ionicons from 'react-native-vector-icons/Ionicons'
import Octicons from 'react-native-vector-icons/Octicons'
import AsyncStorage from '#react-native-async-storage/async-storage'
import AntDesign from 'react-native-vector-icons/AntDesign';
import ImageZoom from 'react-native-image-pan-zoom';
import { UserProvider } from './UserContext'
const AddProduct = ({ route, navigation }) => {
const [count, setCount] = useState(1)
console.log("this is item quantity=>", count);
const prodId = route.params.prodId
console.log('data is coming from route', prodId);
const [prodImg, setProdImg] = useState("")
console.log("this is product image from use state=>", prodImg);
const [productName, setProductName] = useState("")
const [productDesc, setProductDesc] = useState("")
// const [in_stock, setIn_stock] = useState("")
const [availableQty, setAvailableQty] = useState("")
const [basePrice, setBasePrice] = useState("")
const [variations, setVariations] = useState([])
console.log("this is variation data", variations);
const [changePrice, setChangePrice] = useState("")
const [variationid, setVariationid] = useState("")
console.log('this is variation id=>', variationid);
const [selectedVar, setselectedVar] = useState(0)
const [customerId, setCustomerId] = useState("")
console.log("This is customer id ", customerId);
const baseUrl = "https://team.flymingotech.in/azamDeals/public/"
const [loader, setLoader] = useState(false)
const GetProductById = () => {
setLoader(true)
var requestOptions = {
method: 'GET',
redirect: 'follow'
};
fetch(`https://team.flymingotech.in/azamDeals/public/api/readByID/${route.params.prodId}/read`, requestOptions)
.then(response => response.json())
.then(result => {
console.log(result)
setProdImg(result[0].data.product_images)
setProductName(result[0].data.product_name)
setProductDesc(result[0].data.product_desc)
setAvailableQty(result[0].data.available_qty)
setBasePrice(result[0].data.base_price)
// setProductData(result.data)
setVariations(result[0].data?.variations)
// if (result && result.data) {
// setVariations(result.data.variations);
// } else {
// console.log('Could not retrieve data');
// }
setLoader(false)
})
.catch(error => {
console.log('error in getProductbyId api', error)
setLoader(false)
});
}
const getId = async () => {
try {
const customer_id = JSON.parse(await AsyncStorage.getItem("Customer_id"))
console.log("this is getting async storage data", customer_id);
setCustomerId(customer_id)
} catch (error) {
console.log(error);
}
};
useEffect(() => {
getId()
GetProductById()
}, [route.params.prodId])
function increment() {
//setCount(prevCount => prevCount+=1);
setCount(function (prevCount) {
return (prevCount += 1);
});
}
function decrement() {
setCount(function (prevCount) {
if (prevCount > 0) {
return (prevCount -= 1);
} else {
return (prevCount = 0);
}
});
}
const AddCart = async () => {
if (variationid == 0) {
Alert.alert("Please select the product variation")
return false;
} else if (count == 0) {
Alert.alert("Qty cannot be 0")
}
else {
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
var raw = JSON.stringify({
"product_id": prodId,
"item_qty": count,
"item_price": changePrice,
"total_price": "",
"c_id": customerId,
"variation_id": variationid
});
var requestOptions = {
method: 'POST',
headers: myHeaders,
body: raw,
redirect: 'follow'
};
await fetch("https://team.flymingotech.in/azamDeals/public/api/new_cart", requestOptions)
.then(response => response.json())
.then(result => {
console.log(result)
if (result.status == 1) {
Alert.alert('Added to cart')
}
})
.catch(error => console.log('error', error));
}
}
const onSelect = (id) => {
setselectedVar(id)
console.log(id);
}
const images = [
{
url:
'https://raw.githubusercontent.com/AboutReact/sampleresource/master/sample_img.png',
},
{
url:
'https://raw.githubusercontent.com/AboutReact/sampleresource/master/old_logo.png',
},
];
return (
<View style={styles.mainContainer}>
<View style={{ height: 80, backgroundColor: '#006C32', flexDirection: 'row', paddingTop: 25 }}>
<TouchableOpacity onPress={() => navigation.goBack()}>
<AntDesign style={{ paddingLeft: 20 }} name='arrowleft' size={30} color="white" />
</TouchableOpacity>
<Text style={{ paddingLeft: 20, fontSize: 20, color: 'white' }}>Product Detail</Text>
</View>
{/* <SearchHeader /> */}
{loader ?
<View style={{
alignItems: "center",
justifyContent: "center",
height: "90%"
}}>
<ActivityIndicator size={50} color="green" />
</View>
:
<ScrollView>
<View style={{ marginLeft: 15, marginRight: 15 }}>
<View>
{/* <Image style={{ height: 300, width: '100%', borderRadius: 10, marginTop: 10 }}
source={{ uri: prodImg }} /> */}
<ImageZoom
cropWidth={350}
cropHeight={300}
imageWidth={200}
imageHeight={200}>
<Image style={{ width: 200, height: 200 }}
source={{ uri: prodImg }} />
</ImageZoom>
<Text style={{ color: 'black', fontWeight: 'bold', marginTop: 10 }}>{productName}</Text>
<Text style={{ color: 'black', backgroundColor: 'white' }}>{productDesc}</Text>
<Text style={{ color: 'black', backgroundColor: 'white' }} >Stock:{availableQty}</Text>
<Text style={{ color: 'black', backgroundColor: 'white' }} >Base Price:₹{basePrice}</Text>
<Text style={{ color: 'black', backgroundColor: 'white' }} >Variation Price:₹{changePrice}</Text>
{/* <Text style={{ color: 'black', backgroundColor: 'white' }} >Variationid:{variationid}</Text> */}
<View style={{ marginTop: 14 }}>
<Text style={{ color: 'black', fontSize: 18, }}>Size</Text>
<View style={{
flexDirection: 'row',
justifyContent: 'space-around', height: 25
}}>
{/* {console.log("type", productData.variations.length)} */}
<View >
{variations?.length > 0 && variations.map((item, i) => (
<View key={i}>
<TouchableOpacity onPress={() => setChangePrice(item.variation_price,) | setVariationid(item.id) |onSelect(item.id)} style={{
height: 70, width: 120,
borderWidth: 0.5, borderColor: 'grey', borderRadius: 10,
justifyContent: 'center', alignItems: 'center',
backgroundColor: selectedVar === item.id ? "lightgrey" : "#fff"
}}>
<Text style={{ color: 'black', }}>{item.variation_label}</Text>
<Text style={{ color: 'black', }}>{item.variation_weight}</Text>
</TouchableOpacity>
</View>
))}
</View>
{/* <FlatList horizontal
data={productData}
renderItem={(item)=>renderItem(item)}
/> */}
{/* <Pressable onPress={() => getSize('s')} style={[styles.variable, { backgroundColor: size === 's' ? '#D1D1D1' : '#FFF' }]}><Text style={styles.variableValue}>S</Text></Pressable>
<Pressable onPress={() => getSize('m')} style={[styles.variable, { backgroundColor: size === 'm' ? '#D1D1D1' : '#FFF' }]}><Text style={styles.variableValue}>M</Text></Pressable>
<Pressable onPress={() => getSize('l')} style={[styles.variable, { backgroundColor: size === 'l' ? '#D1D1D1' : '#FFF' }]}><Text style={styles.variableValue}>L</Text></Pressable> */}
</View>
</View>
<View style={{ flexDirection: "row", marginTop: 50, justifyContent: 'space-between', paddingBottom: 10 }}>
<View style={styles.countButton}>
<TouchableOpacity onPress={decrement} style={{ alignSelf: 'center', marginLeft: 5 }}>
<Octicons name="dash" size={28} color="black" />
</TouchableOpacity>
<Text style={{ alignSelf: 'center', fontSize: 17, marginLeft: 4, color: 'black' }}>{count}</Text>
<TouchableOpacity onPress={increment} style={{ alignSelf: 'center' }}>
<Ionicons name="add" size={28} color="black" />
</TouchableOpacity>
</View>
<TouchableOpacity onPress={AddCart} style={{
backgroundColor: '#006C32', height: 40
, justifyContent: 'center', alignItems: 'center', width: 150, borderRadius: 5,
}}>
<Text style={{ color: 'white', fontWeight: 'bold' }}>Add to Cart</Text>
</TouchableOpacity>
</View>
{/* <View>
<TouchableOpacity style={{
width: 300, marginTop: 20, backgroundColor: 'darkgreen', height: 50
, borderRadius: 10, justifyContent: 'center', alignItems: 'center', alignSelf: 'center'
}}>
<Text style={{ color: 'white', fontWeight: 'bold' }}>Buy Now</Text>
</TouchableOpacity>
</View> */}
</View>
</View>
</ScrollView>
}
</View>
)
}
const styles = StyleSheet.create({
mainContainer: {
flex: 1,
backgroundColor: 'white'
},
image: {
height: 300, width: '100%',
},
countButton: {
backgroundColor: 'white', height: 40, borderWidth: 0.5, borderColor: 'grey'
, width: 100, flexDirection: 'row', borderRadius: 10, justifyContent: 'space-between',
},
variable: {
padding: 5,
color: 'black',
borderWidth: 1,
borderColor: '#999999',
borderRadius: 4,
},
variableValue: {
fontWeight: '700',
},
})
export default AddProduct
And this is my screen where I am showing the count of the products as a badge using an API it is working it is showing the data but when I refresh the app that time only it shows the count
import { View, Text, StyleSheet } from 'react-native'
import React, { useEffect, useState } from 'react'
import { createBottomTabNavigator } from '#react-navigation/bottom-tabs';
import { getFocusedRouteNameFromRoute } from '#react-navigation/native';
import Ionicons from 'react-native-vector-icons/Ionicons'
import User from 'react-native-vector-icons/FontAwesome'
// screens
import { NavigationContainer } from '#react-navigation/native';
import { createNativeStackNavigator } from '#react-navigation/native-stack'
import Home from '../screens/HomeScreen/Home';
import { CustomerStack, Cart, Profile } from './CustomerStack';
import { Badge } from 'react-native-elements';
import AsyncStorage from '#react-native-async-storage/async-storage';
// Screen Names
const Stack = createNativeStackNavigator();
const Tab = createBottomTabNavigator();
const BottomTabNav = ({ route, navigation }) => {
const [Count, setCount] = useState("")
console.log("this is Count of cart=>",Count);
useEffect(() => {
getCartCount()
}, [])
const getCartCount = async () => {
const customer_id = JSON.parse(await AsyncStorage.getItem("Customer_id"))
var requestOptions = {
method: 'GET',
redirect: 'follow'
};
fetch(`https://team.flymingotech.in/azamDeals/public/api/countCartItems/${customer_id}`, requestOptions)
.then(response => response.json())
.then(result => {
console.log(result)
setCount(result.data)
})
.catch(error => console.log('error', error));
}
<Tab.Screen
name="CustomerStack"
component={CustomerStack}
options={({ route }) => ({ tabBarStyle: getTabBarStyle(route) })} />
const getTabBarStyle = (route) => {
const routeName = getFocusedRouteNameFromRoute(route) ?? 'CustomerStack';
let display = (routeName === 'Player') ? 'none' : 'flex';
return { display }
}
return (
<Tab.Navigator initialRouteName='CustomerStack'
tabBarOptions={{
// activeTintColor: 'red',
inactiveTintColor: 'white',
}}
screenOptions={({ route, }) => ({
tabBarStyle: {
backgroundColor: '#006C32',
},
tabBarIcon: ({ focused, color, size }) => {
let iconName;
let rn = route.name;
if (rn === "CustomDrawer") {
iconName = focused ? 'home' : 'home'
}
else if (rn === "CustomerStack") {
iconName = focused ? 'home' : 'home'
}
else if (rn === "Cart") {
<View style={styles.unreadBadge}>
<Text style={styles.unreadBadgeText}>11</Text>
</View>
iconName = focused ? 'shopping-cart' : 'shopping-cart'
} else if (rn === "Account") {
iconName = focused ? 'user' : 'user'
}
return <User name={iconName} size={size} color={color} />
},
})}>
<Tab.Screen options={{ headerShown: false, tabBarActiveTintColor: 'white', }} name="CustomerStack" component={CustomerStack} />
<Tab.Screen options={{
headerShown: false, tabBarActiveTintColor: 'white',
tabBarBadge: Count
}} name="Cart" component={Cart} />
<Tab.Screen options={{ headerShown: false, tabBarActiveTintColor: 'white', }} name="Account" component={Profile} />
</Tab.Navigator>
)
}
const styles = StyleSheet.create({
unreadBadge: {
backgroundColor: '#FF3250',
position: 'absolute',
left: 20,
bottom: 18,
width: 25,
height: 18,
borderradius: 25,
alignItems: 'center',
justifyContent: 'center',
zIndex: 100, // this one is used to put message notify on top of icon
},
unreadBadgeText: {
color: 'white',
fontWeight: '600',
},
})
export default BottomTabNav
What I was going to try is that keep calling that API every 5 seconds then after calling the API So many times it will give Too many request error .
Whether I should use UseContext or Pass data through both the screen and call API I don't get it!

Why is the checkbox not setting checked and why does console.log is called multiple times?

Here is my Login screen
import {
View,
StyleSheet,
Text,
TouchableWithoutFeedback,
ScrollView,
Platform,
KeyboardAvoidingView,
Alert,
Image,
TouchableOpacity,
} from "react-native";
import * as LocalAuthentication from "expo-local-authentication";
import { CustomCheckBoxInput, CustomTextInput } from "#components/Input";
import { useForm } from "react-hook-form";
import { Ionicons } from "#expo/vector-icons";
import colors from "#config/colors";
import { AppButton } from "#components/Button";
import AppScreen from "#components/AppScreen";
import { loginUser } from "#redux/slices/auth";
import { useCallback, useEffect, useState, memo, useMemo } from "react";
import { useAppDispatch, useAppSelector } from "#hooks/hooks";
import useAuth from "#hooks/useAuth";
import { getItem, removeItem, setItem } from "#config/dataStorage";
import { useFocusEffect, useIsFocused } from "#react-navigation/native";
interface LoginScreenProps {}
const LoginScreen = ({ navigation }: any) => {
const [data, setData] = useState(null);
const { loading, logIn } = useAuth();
const { control, handleSubmit, reset } = useForm();
const focused = useIsFocused();
const getData = async () => {
const data = await getItem("#user_data");
const parsedData = JSON.parse(data);
if (parsedData) setData(parsedData);
};
useEffect(() => {
if (focused) {
getData();
const defaults = {
email: data?.email,
remember: data?.isRemembered,
};
reset(defaults);
}
}, [reset, data?.email, focused]);
console.log(data);
const onSubmit = useCallback(async (data) => {
const response = await logIn(data);
if (data.remember && response.success) {
await setItem(
"#user_data",
JSON.stringify({ email: data.email, isRemembered: data.remember })
);
} else {
await removeItem("#user_data");
}
}, []);
const onFaceId = async () => {
try {
// Checking if device is compatible
const isCompatible = await LocalAuthentication.hasHardwareAsync();
if (!isCompatible) {
throw new Error("Your device isn't compatible.");
}
// Checking if device has biometrics records
const isEnrolled = await LocalAuthentication.isEnrolledAsync();
if (!isEnrolled) {
throw new Error("No Faces / Fingers found.");
}
// Authenticate user
await LocalAuthentication.authenticateAsync();
Alert.alert("Authenticated", "Welcome back !");
} catch (error) {
Alert.alert("An error as occured", error?.message);
}
};
return (
<AppScreen>
<KeyboardAvoidingView
style={{
flex: 1,
paddingHorizontal: 20,
}}
behavior={Platform.OS === "ios" ? "padding" : "height"}
>
<Image
source={require("assets/logo5.png")}
resizeMode="contain"
style={{ position: "absolute", top: 0, left: 0 }}
/>
<ScrollView>
<View
style={{
flexDirection: "column",
marginTop: "10%",
marginBottom: "3%",
}}
>
<View
style={{
flexDirection: "row",
alignItems: "center",
}}
>
<TouchableWithoutFeedback
onPress={() => navigation.navigate("Welcome")}
>
<Ionicons
name="chevron-back-outline"
size={30}
color="#fff"
style={{ marginStart: -10 }}
/>
</TouchableWithoutFeedback>
<Text style={{ color: "white", fontSize: 32 }}>
Welcome back,
</Text>
</View>
</View>
<Text
style={{
color: "white",
fontSize: 18,
fontWeight: "200",
marginBottom: "5%",
}}
>
Please login to your account to continue.
</Text>
<Text style={{ color: "#fff" }}>{data?.email}</Text>
<Text style={{ color: "#fff" }}>{data?.isRemembered.toString()}</Text>
<CustomTextInput
name="email"
control={control}
placeholder="email"
value={data?.email}
textContentType="emailAddress"
label="E-mail"
rules={{ required: "This field is required!" }}
/>
<CustomTextInput
name="password"
control={control}
placeholder="password"
label="Password"
rules={{ required: "This field is required!" }}
secureTextEntry={true}
/>
<CustomCheckBoxInput
control={control}
name="remember"
label="Remember Me"
isChecked={data?.isRemembered}
/>
<AppButton
title="Login"
bgColor={colors.buttonPrimary}
loading={loading}
onPress={handleSubmit(onSubmit)}
style={{ marginTop: 10, marginBottom: 10 }}
/>
<View
style={{ flexDirection: "row", justifyContent: "space-between" }}
>
<TouchableOpacity
activeOpacity={0.7}
style={{ marginBottom: 20, alignSelf: "flex-end" }}
onPress={onFaceId}
>
<Text
style={{
color: colors.buttonPrimary,
fontWeight: "300",
fontSize: 16,
}}
>
Login with Face ID
</Text>
</TouchableOpacity>
<TouchableOpacity
activeOpacity={0.7}
style={{ marginBottom: 20, alignSelf: "flex-end" }}
onPress={() => navigation.navigate("Email")}
>
<Text
style={{
color: colors.smallTextHex,
fontWeight: "600",
fontSize: 16,
}}
>
Forgot Password
</Text>
</TouchableOpacity>
</View>
<View
style={{
flexDirection: "row",
justifyContent: "center",
}}
>
<Text style={{ color: "#fff", fontSize: 16, fontWeight: "200" }}>
New to TickersFund?{" "}
</Text>
<TouchableOpacity
onPress={() => navigation.navigate("Register")}
activeOpacity={0.7}
>
<Text
style={{
color: colors.smallTextHex,
fontWeight: "600",
color: colors.buttonPrimary,
fontSize: 16,
}}
>
Register Here
</Text>
</TouchableOpacity>
</View>
</ScrollView>
</KeyboardAvoidingView>
</AppScreen>
);
};
const styles = StyleSheet.create({
container: {
backgroundColor: colors.background,
// padding: 10,
},
top_container: {},
});
export default LoginScreen;
What I wanted is showing defaultValue for Email and Checkbox if user submits data with remember true
Problem
Email showing but checkbox is not showing checked
multiple console.log() showing
react-native-async-storage: ~1.15
Why am I seeing multiple console.logs and why value is not setting in the CustomCheckBox
export const CustomCheckBoxInput = ({
control,
name,
label,
...props
}: CustomChecboxProps) => {
return (
<Controller
control={control}
name={name}
render={({
field: { value, onChange, onBlur },
fieldState: { error },
}) => (
<BouncyCheckbox
onPress={(value) => {
Haptics.notificationAsync(Haptics.NotificationFeedbackType.Success);
onChange(value);
}}
fillColor={colors.buttonPrimary}
size={18}
unfillColor={colors.background}
style={{ marginTop: 10, marginLeft: 5 }}
text={label}
textStyle={{ fontSize: 18, textDecorationLine: "none" }}
iconStyle={{ borderColor: colors.buttonPrimary, marginRight: -5 }}
{...props}
/>
)}
/>
);
};
Here is my CustomCheckBox component

add current time with text input

enter image description here Iam new with react native,so maybe my question seems silly to all excepts.I want to add current time in text input.(i designd todo app,that show the todo list,now i want to show time in todo list,for eg i enter todo(complete frontend)and add,that contain complete and delete button,now i want to add time in that(task adding time).my code are following below,
import React from 'react';
import {
StyleSheet,
SafeAreaView,
View,
TextInput,
Text,
FlatList,
TouchableOpacity,
Alert,
} from 'react-native';
import Icon from 'react-native-vector-icons/MaterialIcons';
import AsyncStorage from '#react-native-async-storage/async-storage';
const COLORS = {primary: '#1f145c', white: '#fff'};
const App = () => {
const \[todos, setTodos\] = React.useState(\[\]);
const \[textInput, setTextInput\] = React.useState('');
React.useEffect(() => {
getTodosFromUserDevice();
}, \[\]);
React.useEffect(() => {
saveTodoToUserDevice(todos);
}, \[todos\]);
const addTodo = () => {
if (textInput == '') {
Alert.alert('Error', 'Please input todo');
} else {
const newTodo = {
id: Math.random(),
task: textInput,
completed: false,
};
setTodos(\[...todos, newTodo\]);
setTextInput('');
}
};
const saveTodoToUserDevice = async todos => {
try {
const stringifyTodos = JSON.stringify(todos);
await AsyncStorage.setItem('todos', stringifyTodos);
} catch (error) {
console.log(error);
}
};
const getTodosFromUserDevice = async () => {
try {
const todos = await AsyncStorage.getItem('todos');
if (todos != null) {
setTodos(JSON.parse(todos));
}
} catch (error) {
console.log(error);
}
};
const markTodoComplete = todoId => {
const newTodosItem = todos.map(item => {
if (item.id == todoId) {
return {...item, completed: true};
}
return item;
});
setTodos(newTodosItem);
};
const deleteTodo = todoId => {
const newTodosItem = todos.filter(item => item.id != todoId);
setTodos(newTodosItem);
};
const clearAllTodos = () => {
Alert.alert('Confirm', 'Clear todos?', \[
{
text: 'Yes',
onPress: () => setTodos(\[\]),
},
{
text: 'No',
},
\]);
};
const ListItem = ({todo}) => {
return (
<View style={styles.listItem}>
<View style={{flex: 1}}>
<Text
style={{
fontWeight: 'bold',
fontSize: 20,
color: COLORS.primary,
textDecorationLine: todo?.completed ? 'line-through' : 'none',
}}>
{todo?.task}
</Text>
</View>
{!todo?.completed && (
<TouchableOpacity onPress={() => markTodoComplete(todo.id)}>
<View style={\[styles.actionIcon, {backgroundColor: 'green'}\]}>
<Icon name="done" size={20} color="white" />
</View>
</TouchableOpacity>
)}
<TouchableOpacity onPress={() => deleteTodo(todo.id)}>
<View style={styles.actionIcon}>
<Icon name="delete" size={20} color="white" />
</View>
</TouchableOpacity>
</View>
);
};
return (
<SafeAreaView
style={{
flex: 1,
backgroundColor: 'white',
}}>
<View style={styles.header}>
<Text
style={{
fontWeight: 'bold',
fontSize: 20,
color: COLORS.primary,
}}>
TODO APP
</Text>
<Icon name="delete" size={25} color="red" onPress={clearAllTodos} />
</View>
<FlatList
showsVerticalScrollIndicator={false}
contentContainerStyle={{padding: 20, paddingBottom: 100}}
data={todos}
renderItem={({item}) => <ListItem todo={item} />}
/>
<View style={styles.footer}>
<View style={styles.inputContainer}>
<TextInput
value={textInput}
placeholder="Add Todo"
onChangeText={text => setTextInput(text)}
/>
</View>
<TouchableOpacity onPress={addTodo}>
<View style={styles.iconContainer}>
<Icon name="add" color="white" size={30} />
</View>
</TouchableOpacity>
</View>
</SafeAreaView>
);
};
const styles = StyleSheet.create({
footer: {
position: 'absolute',
bottom: 0,
width: '100%',
flexDirection: 'row',
alignItems: 'center',
paddingHorizontal: 20,
backgroundColor: COLORS.white,
},
inputContainer: {
height: 50,
paddingHorizontal: 20,
elevation: 40,
backgroundColor: COLORS.white,
flex: 1,
marginVertical: 20,
marginRight: 20,
borderRadius: 30,
},
iconContainer: {
height: 50,
width: 50,
backgroundColor: COLORS.primary,
elevation: 40,
borderRadius: 25,
justifyContent: 'center',
alignItems: 'center',
},
listItem: {
padding: 20,
backgroundColor: COLORS.white,
flexDirection: 'row',
elevation: 12,
borderRadius: 7,
marginVertical: 10,
},
actionIcon: {
height: 25,
width: 25,
backgroundColor: COLORS.white,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: 'red',
marginLeft: 5,
borderRadius: 3,
},
header: {
padding: 20,
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'space-between',
},
});
export default App;][1]
i got the answer ,answer is following below,
import React from 'react';
import {
StyleSheet,
SafeAreaView,
View,
TextInput,
Text,
FlatList,
TouchableOpacity,
Alert,
} from 'react-native';
import Icon from 'react-native-vector-icons/MaterialIcons';
import AsyncStorage from '#react-native-async-storage/async-storage';
const COLORS = {primary: '#1f145c', white: '#fff'};
const App = () => {
const [todos, setTodos] = React.useState([]);
const [textInput, setTextInput] = React.useState('');
React.useEffect(() => {
getTodosFromUserDevice();
}, []);
React.useEffect(() => {
saveTodoToUserDevice(todos);
}, [todos]);
const addTodo = () => {
if (textInput == '') {
Alert.alert('Error', 'Please input todo');
} else {
const newTodo = {
id: Math.random(),
task: textInput,
completed: false,
time: getCurrentTime()
};
setTodos([...todos, newTodo]);
setTextInput('');
}
};
const saveTodoToUserDevice = async todos => {
try {
const stringifyTodos = JSON.stringify(todos);
await AsyncStorage.setItem('todos', stringifyTodos);
} catch (error) {
console.log(error);
}
};
const getTodosFromUserDevice = async () => {
try {
const todos = await AsyncStorage.getItem('todos');
if (todos != null) {
setTodos(JSON.parse(todos));
}
} catch (error) {
console.log(error);
}
};
***const getCurrentTime = () => {
let today = new Date();
let date = today.getFullYear()+'-'+(today.getMonth()+1)+'-'+today.getDate();
let time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
let dateTime = date + '/' + time;
return dateTime;
}***
const markTodoComplete = todoId => {
const newTodosItem = todos.map(item => {
if (item.id == todoId) {
return {...item, completed: true};
}
return item;
});
setTodos(newTodosItem);
};
const deleteTodo = todoId => {
const newTodosItem = todos.filter(item => item.id != todoId);
setTodos(newTodosItem);
};
const clearAllTodos = () => {
Alert.alert('Confirm', 'Clear todos?', [
{
text: 'Yes',
onPress: () => setTodos([]),
},
{
text: 'No',
},
]);
};
const comdel = () => {
Alert.alert('select status', 'Complete or Delete', [
{
text: 'Delete',
onPress: () => setTodos([]),
},
{
text: 'Complete',
onPress: () => {markTodoComplete(todo.id)}
},
]);
};
const ListItem = ({todo}) => {
return (
<View style={styles.listItem}>
<View style={{flex: 1}}>
<Text
style={{
fontWeight: 'bold',
fontSize: 20,
color: COLORS.primary,
textDecorationLine: todo?.completed ? 'line-through' : 'none',
}}>
{todo?.task}
</Text>
</View>
{/* {!todo?.completed && (
<TouchableOpacity onPress={() => markTodoComplete(todo.id)}>
<View style={[styles.actionIcon, {backgroundColor: 'green'}]}>
<Icon name="done" size={20} color="white" />
</View>
</TouchableOpacity>
)} */}
{/* <TouchableOpacity onPress={() => deleteTodo(todo.id)}>
<View style={styles.actionIcon}>
<Icon name="delete" size={20} color="white" />
</View>
</TouchableOpacity> */}
<View>
<Text>
{todo?.time}
</Text>
</View>
<Icon name="menu" size={40} color="#a9a9a9" onPress={comdel} />
</View>
);
};
return (
<SafeAreaView
style={{
flex: 1,
backgroundColor: 'white',
}}>
<View style={styles.header}>
<Text
style={{
fontWeight: 'bold',
fontSize: 20,
color: COLORS.primary,
}}>
TODO APP
</Text>
<Icon name="delete" size={25} color="red" onPress={comdel} />
</View>
<FlatList
showsVerticalScrollIndicator={false}
contentContainerStyle={{padding: 20, paddingBottom: 100}}
data={todos}
renderItem={({item}) => <ListItem todo={item} />}
/>
<View style={styles.footer}>
<View style={styles.inputContainer}>
<TextInput
value={textInput}
placeholder="Add Todo"
onChangeText={text => setTextInput(text)}
/>
</View>
<TouchableOpacity onPress={addTodo}>
<View style={styles.iconContainer}>
<Icon name="add" color="white" size={30} />
</View>
</TouchableOpacity>
</View>
</SafeAreaView>
);
};
const styles = StyleSheet.create({
footer: {
position: 'absolute',
bottom: 0,
width: '100%',
flexDirection: 'row',
alignItems: 'center',
paddingHorizontal: 20,
backgroundColor: COLORS.white,
},
inputContainer: {
height: 50,
paddingHorizontal: 20,
elevation: 40,
backgroundColor: COLORS.white,
flex: 1,
marginVertical: 20,
marginRight: 20,
borderRadius: 30,
},
iconContainer: {
height: 50,
width: 50,
backgroundColor: COLORS.primary,
elevation: 40,
borderRadius: 25,
justifyContent: 'center',
alignItems: 'center',
},
listItem: {
padding: 40,
backgroundColor: "#d3d3d3",
flexDirection: 'column',
elevation: 12,
borderRadius: 7,
marginVertical: 10,
},
actionIcon: {
height: 25,
width: 25,
backgroundColor: COLORS.white,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: 'red',
marginLeft: 5,
borderRadius: 3,
},
header: {
padding: 20,
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'space-between',
},
});
export default App;

How to refresh the navigation parameters when there are more card components to navigate in React Native

When I click one card component and pass the data to the other page, and when I go back and click another one parameter that I pass from navigation, the navigate does not get changed. Here is my first page to navigate from:
import React,{ useState,useEffect} from 'react';
import { View, Text,TouchableOpacity, Button, StyleSheet ,Image,ScrollView} from 'react-native';
import { FontAwesome, Feather, MaterialIcons,Ionicons } from 'react-native-vector-icons';
const PaymentScreen = ({ route, navigation }) => {
const [paymentList, setPaymentList] = useState([]);
useEffect(() => {
fetch(
"https://run.mocky.io/v3/73958238-7761-4d81-8577-793ff92c0ea1"
)
.then((res) => res.json())
.then((data) => {
setPaymentList(data);
});
}, []);
const showPayment=() =>{
return (
paymentList &&
paymentList
.filter((word) => route.params.Name== word.userID)
.map((Aname, i) => {
return (
<View style={{padding: 8 }}>
<PaymenCard date={Aname.date} discount={Aname.id} cash={Aname.amount} forwardLink={() => navigation.navigate('morePayments',{itemId: Aname.id})}/>
</View>
);
})
)
}
return (
<View style={styles.container}>
<View style={styles.paymentbox}>
<Text style={styles.payment}>Payments</Text>
</View>
<ScrollView>
{ showPayment()}
</ScrollView>
</View>
);
};
export default PaymentScreen;
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor:'#22343C',
},
payment:{
fontSize:42,
color: "white",
fontWeight: "bold",
},
paymentbox:{
marginLeft:32,
paddingBottom: 5
}
});
function PaymenCard(props ){
return(
<TouchableOpacity onPress={props.forwardLink}>
<View style={styles1.cardbox}>
<View style={styles1.square}>
<View style={styles1.dollarbig}>
<MaterialIcons name="monetization-on" color="#FFC542" size={30} />
</View>
</View>
<View style={styles1.datedisc}>
<View style={styles1.date}>
<Text style={styles1.datetext}>{props.date} </Text>
</View>
<View style={styles1.discount}>
<View style={styles1.rocket}>
<FontAwesome name="rocket" color="#FFC542" size={20} />
</View>
<View style={styles1.discountval}>
<Text style={styles1.discounttext}>{props.discount}</Text>
</View>
</View>
</View>
<View style={styles1.cashbox}>
<Text style={styles1.cashtext}>{props.cash}</Text>
</View>
</View>
</TouchableOpacity>
)
}
const styles1 = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#22343C',
},
cardbox: {
height: 115,
width: 345,
backgroundColor: '#30444E',
borderRadius: 25,
marginLeft: 22,
flexDirection: 'row',
},
square: {
height: 57,
width: 59,
borderRadius: 12,
backgroundColor: '#FF565E',
marginTop: 24,
marginLeft: 23,
},
dollarbig: {
marginTop: 15,
alignItems: 'center',
},
datedisc: {
marginTop: 24,
marginLeft: 16,
width: 145,
flexDirection:"column"
},
datetext: {
color: 'white',
fontSize: 14,
},
discount:{
marginTop:15,
flexDirection:"row",
},
rocket:{
},
discountval:{
marginLeft:13
},
discounttext:{
color:"white",
fontSize: 14,
},
cashbox:{
marginTop:30,
marginLeft:25
},
cashtext:{
color:"#FF575F",
fontWeight:"bold",
fontSize:18
}
});
I found the solution. there I have used initial params. so once the value is set it not going to upgrade again. I used react context API to set the updating values globally

flat list error on fetching next page data

I am using redux to get the data from flatlist, in render item function i can see the data is rendering after fetching the page record it throw error
Invariant violation : tried to get frame out of range index 0
in debug statement in renderitem i can see the data is populated and it is printing the data in console. Below is my code
import React, { Component } from 'react'
import { FlatList, StyleSheet, View, Text,Image,ActivityIndicator,
Picker,TouchableOpacity,SectionList,DrawerLayoutAndroid,Alert,
TouchableHighlight,Button} from 'react-native'
import NumericInput from 'react-native-numeric-input'
import {connect} from 'react-redux';
import AlldataJson from './../Data/AllProduct.json'
import {
createDrawerNavigator,
createStackNavigator,
createAppContainer,
} from 'react-navigation';
const mapStateToProps = (state) =>{
// console.log('I am in mapstate to props '+ JSON.stringify(state));
return {
datasource:state.datasource,
isLoading:state.isLoading,
switchValue: state.switchValue,
page:state.page,
rerender:state.rerender,
isFetching: state.isFetching,
search:state.search,
LastSelectedItem:state.LastSelectedItem,
ItemSelected:state.ItemSelected,
setdrawerstate:state.setdrawerstate
}
};
const mapDispatchToProps=(dispatch)=>{
// console.log('i am ni map dispatch to props')
return {
quantitychange:(prodindex, changevalue)=>dispatch({type:"CHANGE_QTY",
index:prodindex,
value:changevalue}),
selectvaluechange:(index,itemvalue,itemindex)=>dispatch({type:"CHANGE_WEIGHT",
index:index,
itemvalue:itemvalue,
itemindex:itemindex}),
ToogleDrawerState:(newState)=>dispatch({type:'TOOGLE_DRAWER',newState:newState}),
taggleSwitch:(value,ind)=>dispatch({type:'TOOGLE_SWITCH',value:value,ind:ind}),
fetchAllData:(AlldataJson)=>dispatch({type:'ALL_DATA',AlldataJson:AlldataJson})
};
};
class DashBoard extends Component {
constructor(props) {
super(props)
console.log('i am in constructor')
console.log('the value getting as props is '+JSON.stringify(props));
// this.selectvaluechange=this.selectvaluechange.bind(this);
// this._opendrawer = this._opendrawer.bind(this);
} //constructor
packageList = (index) =>{
// console.log('i am in package list'+index)
return( this.props.datasource[index].pack.map( (x,j) => {
return( <Picker.Item label={x.Weight} key={j} value={x.packId}/>)}));
}
// Verdana 20
renderItem = ({ item,index }) => {
// console.log('i am in render item index is '+index+' item vale is '+JSON.stringify(item));
return(
<View style={{
flex: 1, flexDirection: 'row', marginBottom: 3,
paddingBottom: 10, paddingTop:10, paddingLeft: 10, backgroundColor: 'white', height: '25%'
}}>
<View style={{ width: '30%' }}>
<Image style={{ resizeMode: 'contain', height: '100%',width:'100%' }}
source={{ uri: this.props.datasource[index].imageUrl }} />
</View>
<View style={{ alignContent: 'center', paddingLeft: 40, width: '65%' }}>
<Text style={{
fontSize: 20, color: 'black', fontWeight: 'bold',
fontFamily: 'Verdana'
}}>
{item.Heading}</Text>
<Text style={{
fontSize: 12, paddingTop: 10, fontFamily: 'Verdana',
color: 'black', fontWeight: 'bold'
}}>{item.Details}</Text>
<View style={{ flex: 1, flexDirection: 'row', paddingTop: 15 }}>
<Text style={{ width: 40, height: 30, fontFamily: 'Verdana', fontWeight: 'bold' }}>Qty :</Text>
<NumericInput
totalHeight={30}
totalWidth={80}
minValue={0}
value={this.props.datasource[index].Qty}
onChange={(value) => this.props.quantitychange(index, value)} />
<Picker
style={{ marginLeft: 10, width: '45%', height: 40, fontFamily: 'Verdana', fontWeight: 'bold' }}
mode="dropdown"
selectedValue={this.props.datasource[index].packselectedValue}
onValueChange={(itemValue, itemIndex) => this.props.selectvaluechange(index, itemValue, itemIndex)}>
{this.packageList(index)}
</Picker>
</View>
<View >
<Text style={{ fontFamily: 'Verdana', fontWeight: 'bold' }}>Price : {this.props.datasource[index].
pack[this.props.datasource[index].packselectedValue].Price}
<Text style={{ fontFamily: 'Verdana', fontWeight: 'bold' }}> Amount : {this.props.datasource[index].
pack[this.pack.datasource[index].packselectedValue].Price *
this.props.datasource[index].Qty}
</Text>
</Text>
</View>
</View>
</View>
)
}
renderSeperator=()=>{
console.log('I am renderseperator the data ')
return(
<View style={{height:1,width:'100%',backgroundColor:'black'}}/>
)
}
onRefresh=()=>{
console.log('I am refreshing the data '+this.props)
// this.setState({isFetching:false})
}
componentDidMount() {
console.log('i am in component didmount ');
const url='./../Data/AllProduct.json'
// ./../Data/AllProduct.json'
fetch(url)
.then((response) => response.json())
.then((responsejson => {
console.log('i am in response json')
fetchAllData(responsejson)}))
//this.setState({ datasource: responsejson })})
.catch((error) => {
console.log('error in fetching the data bhasker')
this.props.fetchAllData(AlldataJson);
console.log('i am after fetchalldata function'+this.props)
})
this.props.navigation.setParams({ opendrawer: this._opendrawer});
}
// data={this.state.page===1?this.state.datasource:[this.state.datasource]}
render() {
// console.log('I am in render '+JSON.stringify(this.props.datasource));
return (
this.props.isLoading ?
<View style={{ flex: 1, justifyContent: 'center', alignContent: 'center' }}>
<ActivityIndicator size='large' color='#330066' animating />
</View> : <View>
<FlatList data={this.props.datasource}
renderItem={(item,index)=>this.renderItem(item,index)}
keyExtractor={item=>item.Id}
debug='yes'/>
</View>
)
}
}
export default connect(mapStateToProps,mapDispatchToProps)(DashBoard);
/* Reducer is */
import * as types from '../Action/ActionType'
import { objectExpression } from '#babel/types';
import Allproduct from './../Data/AllProduct';
const initialstate={
datasource: [],
isLoading:false,
switchValue: true,
page:1,
rerender:true ,
isFetching: false,
search:"" ,
LastSelectedItem:{Item:"",qty:"",weight:""},
ItemSelected:0,
setdrawerstate:true
}
const reducer = (state = initialstate, action) => {
// console.log('i am in reducer '+JSON.stringify(action));
switch (action.type) {
case "CHANGE_QTY":
break;
case "CHANGE_WEIGHT":
break;
case "TOOGLE_DRAWER":
break;
case "TOOGLE_SWITCH":
break;
case "ALL_DATA":
console.log('i am in all data') ;
return {...state,
datasource:action.AlldataJson};
default:
return state;
}
}
export default reducer;
/* All product json is */
[{"Id":"1","Heading":"Ashirvad","Details": "ashirvad Atta - Whole Wheet 10k Pouch",
"imageUrl": "https://www.aashirvaad.com/images/packet-2-right.png", "Qty": 0,
"pack": [{"packId":0,"Weight": "1kg","Price": 25},
{"packId":1,"Weight": "2kg","Price": 50},
{"packId":2,"Weight": "5kg","Price": 125},
{"packId":3,"Weight": "10kg","Price": 250}],
"packselectedValue":0,"isselected": false},
{"Id":"2","Heading": "Tata Salt","Details": "Tata Salt Iodised Salt 1kg Product",
"imageUrl": "http://tatasalt.com/public/front_assets/images/tab-product-img1.png",
"Qty": 0,
"pack": [{"packId":0,"Weight": "1kg","Price": 9.5},{"packId":1,"Weight": "2kg","Price": 19}, {"packId":2,"Weight": "5kg","Price": 47 },
{"packId":3,"Weight": "10kg","Price": 92}],"packselectedValue":0,"isselected": false}]
This is the error i am getting
It occurs because you have debug='yes' for the FlatList, and its data is initially an empty array. To remove the error, either of these should work:
remove the debug prop
add some dummy element to the initial data
render some other component (like a View) if the data array doesn't have any elements
Btw the function parameters/arguments in this line of FlatList
renderItem={(item,index)=>this.renderItem(item,index)}
should have curly braces ({})
renderItem={({item,index})=>this.renderItem({item,index})}
Or better yet, just change it to renderItem={this.renderItem}
Please accept this answer if it solved the problem. Thanks :)
Thanks Amrut Prabha for the help
the problem is in the below code.
<Text style={{ fontFamily: 'Verdana', fontWeight: 'bold' }}> Amount : {this.props.datasource[index].
pack[this.pack.datasource[index].packselectedValue].Price *
this.props.datasource[index].Qty}
pack[this.pack.datasource[index].packselectedValue.price is wrong..
pack[this.props.datasource[index].packselectedValue.price is correct.
i fixed the issue it solve the issue.