Component cannot read JSON properties - react-native

I am trying to figure out why my components are not rendering without errors. I am trying to parse a JSON file that has been saved into a redux store but whenever I call try to reference the redux state through props such as this.props.response.data.specificJSONObject. I will instead get an error that states cannot read property of 'specificJSONObject' of undefined. This problem has plagued all of my components that need the use of the JSON file in the redux store. I initially found that my redux store was not updating(asked question: Redux state not being updated after dispatched actions) when making dispatches but have fixed that and now my redux store is able to store the fetched data it needs but I still get the same error as before.
This is my Summary.js screen for Minimal reproducible code
import React, { Component } from "react";
import {
View,
ImageBackground,
StyleSheet,
Image,
Text,
FlatList
} from "react-native";
import { connect } from "react-redux";
import {
fetchingSuccess,
fetchingRequest,
fetchingFailure,
fetchData
} from "../data/redux/actions/appActions.js";
import PropTypes from "prop-types";
import LinkedName from "./LinkedName";
import ArticleBox from "./ArticleBox";
const styles = StyleSheet.create({
container: {
backgroundColor: "dimgrey",
flex: 1
},
posLeft: {
alignItems: "center",
position: "absolute",
top: 40,
left: 25
},
posRight: {
alignItems: "center",
position: "absolute",
top: 40,
left: 175
},
text: {
textAlign: "center",
color: "#FFF"
},
header_text: {
textAlign: "center",
fontSize: 20,
color: "#FFF"
},
image: {
position: "absolute",
top: 200,
height: 375,
width: 375,
flex: 1
},
topPanel: {
backgroundColor: "rgba(0.0,0.0,0.0,0.9)",
height: 150,
width: 300,
position: "absolute",
alignSelf: "center",
flex: 2,
flexDirection: "column",
borderRadius: 25,
borderWidth: 4
},
midPanel: {
backgroundColor: "rgba(0.0,0.0,0.0,0.9)",
height: 100,
width: 300,
position: "absolute",
bottom: 120,
alignSelf: "center",
flex: 2,
flexDirection: "column",
borderRadius: 25,
borderWidth: 4
}
});
class Summary extends Component<Props> {
constructor(props) {
super(props);
this.state = {
taxonA: this.props.response.articles.taxon_a,
taxonB: this.props.response.articles.taxon_b,
sciNameA: this.props.response.articles.scientific_name_a,
sciNameB: this.props.response.articles.scientific_name_b,
hitRecords: Object.keys(this.props.response.articles.hit_records).map(
key => ({ key, ...this.props.response.articles.hit_records[key] })
),
TTOL:
Math.round(this.props.response.articles.sum_simple_mol_time * 10) / 10,
median: Math.round(this.props.response.articles.sum_median_time * 10) / 10
};
// console.log(STORE, this.props.response.articles);
}
componentDidMount = () => {
console.log("STATE", this.state);
};
render() {
return (
<View style={styles.container}>
<ImageBackground
source={require("../assets/images/timescale.png")}
style={styles.image}
resizeMode="contain"
alignSelf="center"
>
<View style={styles.topPanel}>
<Text style={styles.header_text}>Query Taxa</Text>
<View style={styles.posLeft}>
<Text
style={{ textAlign: "center", color: "#FFF", fontSize: 17 }}
>
Taxon A
</Text>
<Text />
<Text style={styles.text}>{this.state.taxonA}</Text>
<Text />
<LinkedName
url={this.state.hitRecords[0].link_taxon_a}
latinName={this.state.sciNameA}
/>
</View>
<View style={styles.posRight}>
<Text
style={{ textAlign: "center", color: "#FFF", fontSize: 17 }}
>
Taxon B
</Text>
<Text />
<Text style={styles.text}>{this.state.taxonB}</Text>
<Text />
<LinkedName
url={this.state.hitRecords[0].link_taxon_b}
latinName={this.state.sciNameB}
/>
</View>
</View>
<View style={styles.midPanel}>
<Text style={styles.header_text}>Result</Text>
<Text />
<Text style={styles.text}>TTOL: {this.state.TTOL} MYA</Text>
<Text />
<Text style={styles.text}>median: {this.state.median} MYA</Text>
</View>
<View style={{ position: "absolute", bottom: -35, marginLeft: -5 }}>
<FlatList
horizontal
data={this.state.hitRecords}
renderItem={({ item }) => {
return (
<ArticleBox
title={item.title}
year={item.year}
time={item.time}
author={item.author}
/>
);
}}
itemSeparatorComponent={() => (
<View
style={{
backgroundColor: "#ff8c00",
height: 100,
width: 100
}}
/>
)}
/>
</View>
</ImageBackground>
</View>
);
}
}
Summary.propTypes = {
fetchData: PropTypes.func.isRequired,
response: PropTypes.object.isRequired
};
const mapStateToProps = state => {
return { response: state };
};
const mapStateToDispatch = dispatch => ({
fetchData: url => dispatch(fetchData(url))
});
export default connect(
mapStateToProps,
mapStateToDispatch
)(Summary);
This is the function where I reference the Redux state through props
constructor(props) {
super(props);
this.state = {
taxonA: this.props.response.articles.taxon_a,
taxonB: this.props.response.articles.taxon_b,
sciNameA: this.props.response.articles.scientific_name_a,
sciNameB: this.props.response.articles.scientific_name_b,
hitRecords: Object.keys(this.props.response.articles.hit_records).map(
key => ({ key, ...this.props.response.articles.hit_records[key] })
),
TTOL:
Math.round(this.props.response.articles.sum_simple_mol_time * 10) / 10,
median: Math.round(this.props.response.articles.sum_median_time * 10) / 10
};
// console.log(STORE, this.props.response.articles);
}
In this Instance, I built it right when the state was built but in other components, I will set the state through the componentWillMount function and the problem will still persist.
My expected output should be no errors and my components render properly. The received output is the red screen will the error message cannot read property of 'specificJSONObject' of undefined.

The Answer in the question linked up top helps to solve this problem, but will explained here as well.
In my Summary Screen, the problem is being mapped to response. If you see the MapStatetoProps functions is written like this
const mapStateToProps = state => {
return { response: state };
};
but should be written like this
const mapStateToProps = state => {
return { response: state.fetchingStatus };
};
due to how my Redux store is set up and dispatches(can be seen in the question linked above)

Related

I am trying to implement text change and edit ends in TextInput using react-native but it's not quite working. Can any one help me?

I am trying to implement text change and edit ends in TextInput using react-native but it's not quite working.
See the Screenshot Here
Currently, when changing the price by touch input, the price is not affected when click off.
Here are my files
CartItem.js:
import React from "react";
import {
View,
TextInput,
Image,
TouchableOpacity,
StyleSheet,
Platform,
Alert,
} from "react-native";
//Colors
import Colors from "../../../utils/Colors";
//NumberFormat
import NumberFormat from "../../../components/UI/NumberFormat";
//Icon
import { MaterialCommunityIcons } from "#expo/vector-icons";
import CustomText from "../../../components/UI/CustomText";
//PropTypes check
import PropTypes from "prop-types";
export class CartItem extends React.PureComponent {
render() {
const { item, onAdd, onDes, onRemove } = this.props;
const AddItemHandler = async () => {
await onAdd();
};
const sum = +item.item.price * +item.quantity;
const checkDesQuantity = async () => {
if (item.quantity == 1) {
Alert.alert(
"Clear cart",
"Are you sure you want to remove the product from the cart?",
[
{
text: "Cancel",
},
{
text: "Yes",
onPress: onRemove,
},
]
);
} else {
await onDes();
}
};
return (
<View style={styles.container}>
<View style={styles.left}>
<Image
style={{
width: "100%",
height: 90,
resizeMode: "stretch",
borderRadius: 5,
}}
source={{ uri: item.item.thumb }}
/>
</View>
<View style={styles.right}>
<View
style={{ flexDirection: "row", justifyContent: "space-between" }}
>
<CustomText style={styles.title}>{item.item.filename}</CustomText>
<View>
<TouchableOpacity onPress={onRemove}>
<MaterialCommunityIcons name='close' size={20} color='#000' />
</TouchableOpacity>
</View>
</View>
<CustomText style={{ color: Colors.grey, fontSize: 12 }}>
Provided by Brinique Livestock LTD
</CustomText>
<NumberFormat price={sum.toString()} />
<View style={styles.box}>
<TouchableOpacity onPress={checkDesQuantity} style={styles.boxMin}>
<MaterialCommunityIcons name='minus' size={16} />
</TouchableOpacity>
Code that I would like to be fixed starts here.
<View>
<TextInput
keyboardType='numeric'
onEndEditing={AddItemHandler}
style={styles.boxText}>{item.quantity}</TextInput>
</View>
Code that I would like to be fixed ends here.
<TouchableOpacity
onPress={AddItemHandler}
style={styles.boxMin}>
<MaterialCommunityIcons name='plus' size={16} />
</TouchableOpacity>
</View>
</View>
</View>
);
}
}
CartItem.propTypes = {
item: PropTypes.object.isRequired,
onAdd: PropTypes.func.isRequired,
onRemove: PropTypes.func.isRequired,
onDes: PropTypes.func.isRequired,
};
const styles = StyleSheet.create({
container: {
flex: 1,
marginHorizontal: 10,
height: 110,
borderBottomWidth: 1,
borderBottomColor: Colors.light_grey,
flexDirection: "row",
paddingVertical: 10,
alignItems: "center",
backgroundColor: "#fff",
paddingHorizontal: 10,
borderRadius: 5,
marginTop: 5,
},
left: {
width: "35%",
height: "100%",
alignItems: "center",
},
right: {
width: "65%",
paddingLeft: 15,
height: 90,
// overflow: "hidden",
},
title: {
fontSize: 14,
},
box: {
flexDirection: "row",
justifyContent: "space-between",
alignItems: "center",
height: Platform.OS === "ios" ? 30 : 25,
backgroundColor: Colors.grey,
width: 130,
borderRadius: 5,
paddingHorizontal: 15,
marginTop: 5,
},
boxMin: {
width: "30%",
alignItems: "center",
},
boxText: {
fontSize: 16,
backgroundColor: Colors.white,
padding: 5,
},
});
Use onBlur instead of onEndEditing.
How should the input end triggered?
After a time?
When user hits enter?
When user taps anywhere to close software keyboard?
Instead of
onEndEditing={AddItemHandler}
Use:
onBlur={(e) => {AddItemHandler(e.nativeEvent.text)}}
And ensure that AddItemHandler can handle the value in e.nativeEvent.text.

Conditional rendering in react native using map function

I am trying to build a notification page where notifications are being fetched from a remote server using the Notification function, so I initially set the notificationLoaded to false in order to use an ActivityLoader before rendering the notification to the page.
But I am confused about how I can render an ActivityLoader before the notificationLoaded state is set to true.
Thanks in advance
import React, { Component } from 'react';
import {
StyleSheet,
ScrollView,
Dimensions,
Text,
ActivityIndicator,
TouchableOpacity,
TextInput,
View,
StatusBar,
ImageBackground,
KeyboardAvoidingView,
AsyncStorage,
} from 'react-native';
import { Ionicons } from '#expo/vector-icons';
import { Font } from 'expo';
import { createStackNavigator, createAppContainer } from 'react-navigation';
import { KeyboardAwareView } from 'react-native-keyboard-aware-view';
const { height, width } = Dimensions.get('window');
export default class Notification extends Component {
constructor(props) {
super(props);
this.state = {
notification: [],
notificationLoaded: false,
};
}
Notification = () => fetch('http://texotrack.com/api/user/notification.php', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
action: 'fetch',
}),
}).then(response => response.json()).then((responseJsonFromServer) => {
console.log(responseJsonFromServer);
this.setState({
notification: responseJsonFromServer,
notificationLoaded: true,
});
})
componentDidMount() {
this.Notification();
AsyncStorage.getItem('key').then((data) => {
const val = JSON.parse(data);
this.setState({
username: data.name,
photo: data.photo,
email: data.email,
userId: data.id,
address: data.address,
});
});
}
render() {
const notificationList = this.state.notification.map(data => (
<View key={data.msg_id} style={styles.notification}>
<View style={{
display: 'flex', flexDirection: 'row',
}}
>
<Text style={{ color: 'green' }}><Ionicons size={20} color="green" name="ios-notifications" /></Text>
<Text style={{
color: '#c9c9c9', fontSize: 15, fontWeight: 'bold', marginLeft: 5,
}}
>
{data.date_sent}
</Text>
</View>
<View style={styles.notificationBody}>
<Text style={{ color: '#000', fontSize: 16 }}>{data.message}</Text>
</View>
<View style={styles.lineStyle} />
</View>
));
return (
<View style={styles.container}>
<StatusBar
style={{ height: 30 }}
backgroundColor="black"
/>
<View elevation={5} style={styles.headers}>
<Text style={{
fontSize: 25, color: 'green', textTransform: 'uppercase', fontWeight: 'bold',
}}
>
Notification
</Text>
<Text style={styles.topIcon} onPress={this.GoHome}>
<Ionicons name="md-home" size={25} color="black" />
</Text>
</View>
<View style={{ flex: 1, margin: 5 }}>
<ScrollView alwaysBounceVertical contentContainerStyle={{ flexGrow: 1 }} enabled bounces>
{notificationList}
</ScrollView>
</View>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
},
lineStyle: {
borderWidth: 0.3,
borderColor: '#c9c9c9',
margin: 10,
},
headers: {
height: 50,
marginBottom: 10,
display: 'flex',
flexDirection: 'row',
justifyContent: 'space-between',
textAlignVertical: 'center',
padding: 10,
shadowColor: '#444',
shadowOffset: {
width: 0,
height: 60,
},
shadowRadius: 5,
shadowOpacity: 1.0,
backgroundColor: '#fff',
},
topIcon: {
marginTop: 3,
fontWeight: 'bold',
},
content: {
margin: 10,
flex: 1,
},
notification: {
height: 70,
padding: 10,
},
});
This is what you call conditional rendering. This can be achieved simply by using if conditions in your render function like:
render(){
// if loading true render Loader
if (this.state.notificationStateLoaded === true) {
return(
<ActivityLoader>
)
} else { // when loading false render the other component
return(
<WhateverComponentWhenDataHasArrived/>
)
}
}
React's documentation is pretty cool. Check this official link for conditional rendering
https://reactjs.org/docs/conditional-rendering.html
I dont understand what you need to do in your map function but to do a conditional rendering inside your render you can do :
<View>
{someCondition&& <Text>Hello</Text>}
</View>
else
<View>
{someCondition? <Text>Condition True</Text> : <Text>Condition false</Text>}
</View>

I can't get any result or errors when i'm drawing signatures on expo app

i'm creating a small react native app using expo, I am trying to run the example given at https://www.npmjs.com/package/react-native-signature-canvas for drawing signatures, i'm getting an interface but i can't draw and i'm not getting any result.
My code:
import React from 'react';
import { StyleSheet, Text, View, Image } from 'react-native';
import Signature from 'react-native-signature-canvas';
class SignatureScreen extends React.Component {
constructor(props) {
super(props);
this.state = { signature: null };
}
handleSignature = signature => {
this.setState({ signature });
};
render() {
const style = `.m-signature-pad--footer
.button {
background-color: blue;
color: #FFF;
}`;
return (
<View style={{ flex: 1 }}>
<View style={styles.preview}>
{this.state.signature ? (
<Image
resizeMode={"contain"}
style={{ width: 335, height: 114 }}
source={{ uri: this.state.signature }}
/>
) : null}
</View>
<Signature
onOK={this.handleSignature}
descriptionText="Sign"
clearText="Clear"
confirmText="Save"
webStyle={style}
/>
</View>
);
}
}
export default SignatureScreen;
const styles = StyleSheet.create({
preview: {
width: 335,
height: 114,
backgroundColor: "#F8F8F8",
justifyContent: "center",
alignItems: "center",
marginTop: 15
},
previewText: {
color: "#FFF",
fontSize: 14,
height: 40,
lineHeight: 40,
paddingLeft: 10,
paddingRight: 10,
backgroundColor: "#69B2FF",
width: 120,
textAlign: "center",
marginTop: 10
}
});
Am I missing something?
could you try this code?
handleSignature = signature => {
console.log(signature);
this.setState({ signature });
};
...
render() {
return (
<View style={{ flex: 1 }}>
<View style={styles.preview}>
{this.state.signature ? (
<Image
resizeMode={"contain"}
style={{ width: 335, height: 114 }}
source={{ uri: this.state.signature }}
/>
) : null}
</View>
<SignatureScreen onOK={this.handleSignature} />
</View>
);
}
}

React Native Flatlist overlapping footer?

I'm getting started with React Native and writing an app. The problem I'm having a problem with the layout/styling. This is a simplified version to show my difficulty.
The Flatlist doesn't know where it's bottom is, it is overlapping the Footer component. I've messed around with it but can't get it to work properly.
import React, { Component } from 'react'
import { FlatList, StyleSheet, Text, View } from 'react-native'
class Header extends Component {
render() {
return (
<View style={styles.headerContainer}>
<Text style={styles.headerText}> </Text>
<Text style={styles.headerText}>
This is the page header!
</Text>
</View>
)
}
}
class Footer extends Component {
render() {
return (
<View style={styles.footerContainer}>
<Text style={styles.footerText}>
This is the page footer!
</Text>
</View>
)
}
}
let myData = [];
for (let i=1; i<=30; i++) {
myData.push({ key: ('My item ' + i) })
}
export default class App extends Component {
render() {
return (
<View style={styles.container}>
<Header />
<View style={styles.listWrapper}>
<FlatList
contentContainerStyle={styles.listContainer}
data={myData}
renderItem={({item}) => <Text style={styles.listItem} >{item.key}</Text>}
contentInset={{top: 0, left: 0, bottom: 50, right: 0}}
/>
</View>
<Footer />
</View>
)
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: 'pink'
},
headerContainer: {
backgroundColor: '#333',
height: 60,
},
headerText: {
textAlign: 'center',
fontSize: 20,
color: '#999'
},
listWrapper: {
flex: 1
},
listContainer: {
backgroundColor: 'lightblue',
},
listItem: {
color: 'red',
fontSize: 28
},
footerContainer: {
backgroundColor: '#333',
position: 'absolute',
left: 0,
right: 0,
bottom: 0,
flex: 1,
height: 20
},
footerText: {
textAlign: 'center',
fontSize: 14,
color: '#999'
}
})
The only solution I have is to add the prop:
ListFooterComponent={<View style={{ height: 20 }} />}
to the Flatlist, giving it the same height as the Footer, so it would take up that space. That works, but it seems inelegant. Is there a better way to do it, like with the CSS?
Thanx.

TextInput length counter in react-native

I have a TextInput with maxLength 100 in my scene, and I want to add a counter below which shows something like "38/100", auto-updating with 'onChangeText'.
So I have to figure out the length of the input value, somehow store it in this.state.textLength while storing the value itself to this.state.text, but I don't know how to do this in "onChangeText = {(text) => ...}" function.
Here is my simplified code:
export class RequestScene extends Component {
constructor() {
super();
this.state={
text: '',
textLength: 0,
category: '',
time: ''
};
}
render(){
return(
<View style={{
flex: 1,
flexDirection: 'column',
justifyContent: 'center',
alignItems: 'center'
}}>
<View style={{
height: 200
}}>
<TextInput style={{
height: 200,
width: 360,
borderColor: 'lightgray',
borderWidth: 1,
padding: 3,
borderRadius: 3,
fontSize: 24}}
maxLength={100}
placeholder='무슨 상황인지 간단하게 써주세요'
multiline={true}
// this is where I am stuck. What should I do with 'textLength'?
onChangeText={
(text)=>this.setState({text})
(text)=>this.setState({textLength})
}
/>
<Text style={{
fontSize:10,
color:'lightgrey',
textAlign: 'right'
}}>
// currently this counter only shows '0/100'
{this.state.textLength}/100
</Text>
The onChangeText() function returns a string. You can do something like:
const maxLength = 100;
this.setState({
textLength: maxLength - text.length,
text, // same as `text: text`
});
To make your code easier to read, you can call a separate method within your onChangeText handler which updates textLength the following way:
export class RequestScene extends Component {
constructor() {
super();
this.maxLength = 100;
this.state={
textLength: 0,
};
}
onChangeText(text){
this.setState({
textLength: this.maxLength - text.length
});
}
render(){
return (
<View style={{
flex: 1,
flexDirection: 'column',
justifyContent: 'center',
alignItems: 'center'
}}>
<View style={{
height: 200
}}>
<TextInput style={{
height: 200,
width: 360,
borderColor: 'lightgray',
borderWidth: 1,
padding: 3,
borderRadius: 3,
fontSize: 24}}
maxLength={100}
placeholder='무슨 상황인지 간단하게 써주세요'
multiline={true}
onChangeText={this.onChangeText.bind(this)}
/>
<Text style={{
fontSize:10,
color:'lightgrey',
textAlign: 'right'
}}>
// currently this counter only shows '0/100'
{this.state.textLength}/100
</Text>
</View>
</View>
);
}
}
To get length of input field try
handleEmailOtp = emailOtpString => {
this.setState({emailOtp: emailOtpString});
const otpLength = emailOtpString.length.toString(); //here
otpLength == 6
? this.setState({otpTyped: true})
: this.setState({otpTyped: false});
};
import React, { Component } from 'react'
import { View, Text, TextInput } from 'react-native'
export default class App extends Component {
state = {
text: ''
}
render() {
return (
<View style={{ padding: 10 }}>
<TextInput style={{ borderWidth: 1 }} numberOfLines={3} maxLength={100} multiline={true} onChangeText={(text) => this.setState({ text: text })} />
<Text>{100 - this.state.text.length}/100 Characters</Text>
</View>
)
}
}