Realm React Native get crash - javascript

I am using Realm for the first time, I have written the simple code in app.js
import React, { Component } from 'react';
import { StyleSheet, Platform, View, Image, Text, TextInput, TouchableOpacity, Alert } from 'react-native';
var Realm = require('realm');
let realm ;
export default class App extends Component{
constructor(){
super();
this.state = {
Student_Name : '',
Student_Class : '',
Student_Subject : ''
}
realm = new Realm({
schema: [{name: 'Student_Info',
properties:
{
student_id: {type: 'int', default: 0},
student_name: 'string',
student_class: 'string',
student_subject: 'string'
}}]
});
}
add_Student=()=>{
realm.write(() => {
var ID = realm.objects('Student_Info').length + 1;
realm.create('Student_Info', {
student_id: ID,
student_name: this.state.Student_Name,
student_class: this.state.Student_Class,
student_subject : this.state.Student_Subject
});
});
Alert.alert("Student Details Added Successfully.")
}
render() {
var A = realm.objects('Student_Info');
var myJSON = JSON.stringify(A);
return (
<View style={styles.MainContainer}>
<TextInput
placeholder="Enter Student Name"
style = { styles.TextInputStyle }
underlineColorAndroid = "transparent"
onChangeText = { ( text ) => { this.setState({ Student_Name: text })} }
/>
<TextInput
placeholder="Enter Student Class"
style = { styles.TextInputStyle }
underlineColorAndroid = "transparent"
onChangeText = { ( text ) => { this.setState({ Student_Class: text })} }
/>
<TextInput
placeholder="Enter Student Subject"
style = { styles.TextInputStyle }
underlineColorAndroid = "transparent"
onChangeText = { ( text ) => { this.setState({ Student_Subject: text })} }
/>
<TouchableOpacity onPress={this.add_Student} activeOpacity={0.7} style={styles.button} >
<Text style={styles.TextStyle}> CLICK HERE TO ADD STUDENT DETAILS </Text>
</TouchableOpacity>
<Text style={{marginTop: 10}}>{myJSON}</Text>
</View>
);
}
}
const styles = StyleSheet.create({
MainContainer :{
flex:1,
alignItems: 'center',
justifyContent: 'center',
paddingTop: (Platform.OS) === 'ios' ? 20 : 0,
margin: 10
},
TextInputStyle:
{
borderWidth: 1,
borderColor: '#009688',
width: '100%',
height: 40,
borderRadius: 10,
marginBottom: 10,
textAlign: 'center',
},
button: {
width: '100%',
height: 40,
padding: 10,
backgroundColor: '#4CAF50',
borderRadius:7,
marginTop: 12
},
TextStyle:{
color:'#fff',
textAlign:'center',
}
});
Now I am getting the error like this in picture http://prntscr.com/mym0zo, as I have already said, I am using the realm for the very first time, so can't understand the problem.
Please help me get this resolved.
My dependancies are
"dependencies": {
"react": "16.8.3",
"react-native": "0.59.1",
"realm": "^2.25.0"
},

Related

How to create text border radius without wrap view in React Native?

In React-Native, how do I set borderRadius to Text-components?
I've tried using borderRadius in text stylesheet but it not work:
import { formatPhone, mapNameWithLocalContact } from '#chat/common/Utils/ChatUtils';
import ChatFunctions from '#chat/service/ChatFunctions';
import { Colors, Text } from '#momo-platform/component-kits';
import React from 'react';
import { StyleSheet, View, TextStyle } from 'react-native';
import { parseValue } from 'react-native-controlled-mentions';
import { MessageText } from 'react-native-gifted-chat';
// #ts-ignore
import ParsedText from 'react-native-parsed-text';
import { partTypes } from '../menstions';
const textStyle = {
fontSize: 16,
lineHeight: 20,
marginTop: 5,
marginBottom: 5,
marginLeft: 10,
marginRight: 10,
};
const styles = {
left: StyleSheet.create({
container: {},
text: {
color: 'black',
...textStyle,
},
link: {
color: 'black',
textDecorationLine: 'underline',
},
textMention: {
color: Colors.pink_05_b,
fontWeight: 'bold',
},
mentionMe: isMe =>
isMe
? {
color: Colors.white,
backgroundColor: Colors.pink_05_b,
}
: {},
}),
right: StyleSheet.create({
container: {},
text: {
color: 'white',
...textStyle,
},
link: {
color: 'white',
textDecorationLine: 'underline',
},
textMention: {
color: 'white',
fontWeight: 'bold',
},
mentionMe: () => ({}),
}),
};
export default class MessageTextCustom extends MessageText {
constructor() {
super(...arguments);
}
render() {
const linkStyle = [
styles[this.props.position].link,
this.props.linkStyle && this.props.linkStyle[this.props.position],
];
const { parts } = parseValue(this.props.currentMessage.text, partTypes);
return (
<View
style={[
styles[this.props.position].container,
this.props.containerStyle && this.props.containerStyle[this.props.position],
]}
>
<ParsedText
style={[
styles[this.props.position].text,
this.props.textStyle && this.props.textStyle[this.props.position],
this.props.customTextStyle,
]}
parse={[
...this.props.parsePatterns(linkStyle),
{ type: 'url', style: linkStyle, onPress: this.onUrlPress },
{ type: 'phone', style: linkStyle, onPress: this.onPhonePress },
{ type: 'email', style: linkStyle, onPress: this.onEmailPress },
]}
childrenProps={{ ...this.props.textProps }}
>
{this.props.isGroup ? (
<Text>
{parts.map(({ text, partType, data }, index) =>
partType ? (
<Text
key={`${index}-${data?.trigger ?? 'pattern'}`}
style={[
styles[this.props.position].textMention,
styles[this.props.position].mentionMe(
formatPhone(data.id) === ChatFunctions.phoneNumber
),
]}
onPress={() =>
this.props.onPressMenstion &&
this.props.onPressMenstion(data.id)
}
>
{`${data?.trigger}${mapNameWithLocalContact({
phone: data?.id,
name: data?.name,
})}`}
</Text>
) : (
<Text
key={index}
style={[
styles[this.props.position].text,
this.props.textStyle &&
this.props.textStyle[this.props.position],
this.props.customTextStyle,
]}
>
{text}
</Text>
)
)}
</Text>
) : (
this.props.currentMessage.text
)}
</ParsedText>
</View>
);
}
}
My expected style
I cannot use view to wrap this text because my text component is wrap by other text component
I've worked on it on snack you can check out this link and make sure you wrap those text with a View and use
flexDirection: 'row';
alignItems: 'center';
So to stop the View from filling the screen 100% add
alignSelf: 'start';
Checkout this link to see the code I've written for this
https://snack.expo.dev/#rajibola/spontaneous-beef-jerky
For TextStyle, borderTopRightRadius, borderTopLeftRadius, borderBottomRightRadius, borderBottomLeftRadius don't work. Only borderRadius works.
Maybe it's a bug!

Unable to update state in react native component using onChangeText

I have been trying to update the email and password value on submitting the form
so that I can pass them in my login API parameters. But I have tried almost everything, the value of this.state won't just update. Every time I try to print the value in console log e.g: cosole.log(this.state.email), it prints empty string i.e the default value set previously.
Here is my code below:
login.js
import React, { Component } from 'react';
import { ThemeProvider, Button } from 'react-native-elements';
import BliszFloatingLabel from './BliszFloatingLabel'
import {
StyleSheet,
Text,
View,
Image,
TextInput,
Animated,
ImageBackground,
Linking
} from 'react-native';
const domain = 'http://1xx.xxx.xx.xxx:8000';
class Login extends Component {
state = {
email: '',
password: '',
}
LoginAPI = (e,p) => {
console.log(e, "####")
}
handleEmail = (text) => {
this.setState({ email: text })
}
handlePassword = (text) => {
this.setState({ password: text })
}
goToSignUpScreen=() =>{
this.props.navigation.navigate('SignUpScreen');
};
goToForgotPasswordScreen=() =>{
this.props.navigation.navigate('ForgotPasswordScreen');
};
render() {
return (
<View style={styles.container} >
<ImageBackground source={require('../bgrndlogin.jpeg')} style={styles.image} >
<View style={styles.heading}>
<Image style={styles.logo} source={require('../loginlogo.png')} />
<Text style={styles.logoText}>Login</Text>
<Text style={styles.logodesc}>Please Login to continue --></Text>
</View>
<View style={styles.form_container}>
<BliszFloatingLabel
label="Email Id"
value={this.state.email}
onChangeText = {this.handleEmail}
onBlur={this.handleBluremail}
/>
<BliszFloatingLabel
label="Password"
value={this.state.password}
onChangeText = {this.handlePassword}
onBlur={this.handleBlurpwd}
secureTextEntry={true}
/>
<ThemeProvider theme={theme}>
<Button buttonStyle={{
opacity: 0.6,
backgroundColor: '#CC2C24',
borderColor: 'white',
borderWidth: 1,
width: 200,
height: 50,
marginTop: 30,
marginLeft: '20%',
alignItems: 'center',
justifyContent: "center"
}}
title="Login"
type="outline"
onPress = {
() => this.LoginAPI(this.state.email, this.state.password)
}
/>
</ThemeProvider>
<Text style={{
marginTop: 70,
color: '#CC2C24',
fontSize: 16,
fontWeight: "bold"
}}
onPress={
this.goToForgotPasswordScreen
}>
Forgot Password?
</Text>
<Text style={{
marginTop: 20,
color: '#CC2C24',
fontSize: 16,
fontWeight: "bold"
}}
onPress={
this.goToSignUpScreen
}>
Don't have an Account?
</Text>
</View>
</ImageBackground>
</View>
)
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
},
logo: {
width: 115,
height: 50,
},
logoText: {
color: 'white',
fontSize: 36,
fontWeight: "bold"
},
logodesc: {
color: '#CC2C24',
fontSize: 18,
fontWeight: "bold"
},
heading: {
flex: 3,
marginLeft:20,
marginTop:30
},
form_container: {
flex: 7,
marginLeft:20,
marginTop:30,
marginRight: 20,
},
image: {
flex: 1,
resizeMode: "cover",
justifyContent: "center"
},
});
const theme = {
Button: {
titleStyle: {
color: 'white',
fontWeight: "bold",
fontSize: 18
},
},
};
export default Login;
I have created a common form as below which I inherit everywhere :
BliszFloatingLabel.js
import React, { Component } from 'react';
import {
Text,
View,
TextInput,
Animated,
} from 'react-native';
class BliszFloatingLabel extends Component {
state = {
entry: '',
isFocused: false,
};
UNSAFE_componentWillMount() {
this._animatedIsFocused = new Animated.Value(0);
}
handleInputChange = (inputName, inputValue) => {
this.setState(state => ({
...state,
[inputName]: inputValue // <-- Put square brackets
}))
}
handleFocus = () => this.setState({ isFocused: true })
handleBlur = () => this.setState({ isFocused: true?this.state.entry!='' :true})
handleValueChange = (entry) => this.setState({ entry });
componentDidUpdate() {
Animated.timing(this._animatedIsFocused, {
toValue: this.state.isFocused ? 1 : 0,
duration: 200,
useNativeDriver: true,
}).start();
}
render() {
// console.log(this.state.entry)
const { label, ...props } = this.props;
const { isFocused } = this.state;
const labelStyle = {
position: 'absolute',
left: 0,
top: !isFocused ? 40 : 0,
fontSize: !isFocused ? 16 : 12,
color: 'white',
};
return (
<View style={{ paddingTop: 20,paddingBottom:20 }}>
<Text style={labelStyle}>
{label}
</Text>
<TextInput
{...props}
style={{
height: 50, fontSize: 16, color: 'white', borderBottomWidth: 1, borderBottomColor: "white"
}}
value={this.state.entry}
onChangeText={this.handleValueChange}
onFocus={this.handleFocus}
onBlur={this.handleBlur}
blurOnSubmit
/>
</View>
)
}
}
export default BliszFloatingLabel;
Instead of passing onChangeText like this onChangeText={this.handleValueChange} pass in a callback in BliszFloatingLabel and also in Login component.
onChangeText={(text)=>this.handleValueChange(text)}
Snack with the fixture.
https://snack.expo.io/#waheed25/d16fb3

Add items to FlatList dynamically in React Native

I have a FlatList with two items. I need to append this list with another elements. When the user clicks on the button, the data from the text inputs should appear in the end of the FlatList. So, I've tried to push data object to the end of the list's array, but new item replaces the last one.
import React, { useState } from 'react';
import { Text, View, StyleSheet, Button } from 'react-native';
import { FlatList } from 'react-native-gesture-handler';
export default function HomeScreen() {
var initialElements = [
{ id : "0", text : "Object 1"},
{ id : "1", text : "Object 2"},
]
const [exampleState, setExampleState] = useState(initialElements);
const [idx, incr] = useState(2);
const addElement = () => {
var newArray = [...initialElements , {id : toString(idx), text: "Object " + (idx+1) }];
initialElements.push({id : toString(idx), text: "Object " + (idx+1) });
incr(idx + 1);
setExampleState(newArray);
}
return (
<View style={styles.container}>
<FlatList
keyExtractor = {item => item.id}
data={exampleState}
renderItem = {item => (<Text>{item.item.text}</Text>)} />
<Button
title="Add element"
onPress={addElement} />
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
width: '100%',
borderWidth: 1
},
});
import React, { useState } from 'react';
import { Text, View, StyleSheet, Button } from 'react-native';
import { FlatList } from 'react-native-gesture-handler';
export default function HomeScreen() {
var initialElements = [
{ id : "0", text : "Object 1"},
{ id : "1", text : "Object 2"},
]
const [exampleState, setExampleState] = useState(initialElements)
const addElement = () => {
var newArray = [...initialElements , {id : "2", text: "Object 3"}];
setExampleState(newArray);
}
return (
<View style={styles.container}>
<FlatList
keyExtractor = {item => item.id}
data={exampleState}
renderItem = {item => (<Text>{item.item.text}</Text>)} />
<Button
title="Add element"
onPress={addElement} />
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
width: '100%',
borderWidth: 1
},
});
You are just changing the listElements array. This will NOT trigger the re rendering of the component and hence the flat list will be unchanged.
Create a state variable in the component and store your data in that so that any modification results in re rendering.
I fixed the problem of replacing elements by changing array into a state variable.
import React, { useState } from 'react';
import { Text, View, StyleSheet, Button } from 'react-native';
import { FlatList } from 'react-native-gesture-handler';
export default function HomeScreen() {
const [initialElements, changeEl] = useState([
{ id : "0", text : "Object 1"},
{ id : "1", text : "Object 2"},
]);
const [exampleState, setExampleState] = useState(initialElements);
const [idx, incr] = useState(2);
const addElement = () => {
var newArray = [...initialElements , {id : idx, text: "Object " + (idx+1) }];
incr(idx + 1);
console.log(initialElements.length);
setExampleState(newArray);
changeEl(newArray);
}
return (
<View style={styles.container}>
<FlatList
keyExtractor = {item => item.id}
data={exampleState}
renderItem = {item => (<Text>{item.item.text}</Text>)} />
<Button
title="Add element"
onPress={addElement} />
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
width: '100%',
borderWidth: 1
},
});
i fixed it by defining the array outside the export function
import React, { useState } from 'react'
import { StyleSheet, View, TextInput, TouchableOpacity, Text, FlatList } from 'react-native'
let tipArray = [
{key: '1', tip: 20},
{key: '2', tip: 12}
]
const screen = function tipInputScreen( {navigation} ) {
const [ tip, setTip ] = useState('')
const addTip = ()=>{
if(tip == "")return
tipArray.push({key: (tipArray.length + 1).toString(), tip})
setTip('')
}
const logInput = (input)=>{
setTip(input)
}
const renderTip = ({ item }) => {
return(
<TouchableOpacity style={styles.listItem}>
<Text style={styles.buttonText}>{`${item.tip} $`}</Text>
</TouchableOpacity>)
}
return (
<View
style={styles.background}>
<TextInput
style={styles.input}
keyboardType={'number-pad'}
keyboardAppearance={'dark'}
onChangeText={logInput}
value={tip}
/>
<TouchableOpacity
style={styles.redButton}
onPress={addTip}>
<Text style={styles.buttonText}>Add Tip</Text>
</TouchableOpacity>
<FlatList
data={tipArray}
renderItem={renderTip}
style={styles.flatList}
/>
</View>
)
}
const styles = StyleSheet.create({
background: {
backgroundColor: 'grey',
paddingTop: Platform.OS === "android" ? 25:0,
width: '100%',
height: '100%',
alignItems: 'center'
},
input: {
marginTop:40,
color:'white',
fontSize:30,
backgroundColor: "#2e2a2a",
height: 50,
width: '90%',
textDecorationColor: "white",
borderColor: 'black',
borderWidth: 2
},
flatList:{
width: "100%"
},
listItem: {
width: "90%",
height: 50,
backgroundColor: "#2e2e2e",
borderRadius: 25,
marginVertical: 4,
marginHorizontal: "5%",
justifyContent: "center"
},
listItemTitle: {
color: "white",
textAlign: "center",
fontSize: 18
},
redButton: {
justifyContent: "center",
width: "90%",
height: 50,
backgroundColor: "red",
borderRadius: 25,
marginHorizontal: 20,
marginVertical: 10
},
buttonText: {
color: "white",
textAlign: "center",
fontSize: 18
}
})
export default screen;
this was part of an larger app, but it should do the trick, I hope it helps

Declaring array for use in React Native AutoComplete search engine

Not sure where I go about declaring the array with which I want to search from, any assistance would be appreciated. I believe my issue is that I am declaring the "services' array in the incorrect area but I am not sure where else to put it! Or if the commas are the right character to be using in between strings/services
import React, { useState, Component } from 'react';
import { StyleSheet, StatusBar, View, Text, Button, TouchableOpacity } from 'react-native';
import AutoComplete from 'react-native-autocomplete-input';
class CareProviderSequenceScreen extends Component {
constructor (props) {
super (props);
this.state = {
services: [],
query: '',
}
}
render() {
const query = this.state;
const services = {
"Pick up my Prescription",
'Pick up groceries',
'Pick up dry cleaning',
'Pick up my pet',
}
return (
<View style={styles.container}>
<Autocomplete
autoCapitalize="none"
autoCorrect={false}
containerStyle={styles.autocompleteContainer}
//data to show in suggestion
data={services.length === 1 && comp(query, services[0].title) ? [] : services}
//default value if you want to set something in input
defaultValue={query}
/*onchange of the text changing the state of the query which will trigger
the findFilm method to show the suggestions*/
onChangeText={text => this.setState({ query: text })}
placeholder="Enter your need"
renderItem={({ item }) => (
//you can change the view you want to show in suggestion from here
<TouchableOpacity onPress={() => this.setState({ query: item.title })}>
<Text style={styles.itemText}>
{item.title} ({item.release_date})
</Text>
</TouchableOpacity>
)}
/>
<View style={styles.descriptionContainer}>
{services.length > 0 ? (
<Text style={styles.infoText}>{this.state.query}</Text>
) : (
<Text style={styles.infoText}>Enter The Film Title</Text>
)}
</View>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
backgroundColor: '#F5FCFF',
flex: 1,
padding: 16,
marginTop: 40,
},
autocompleteContainer: {
backgroundColor: '#ffffff',
borderWidth: 0,
},
descriptionContainer: {
flex: 1,
justifyContent: 'center',
},
itemText: {
fontSize: 15,
paddingTop: 5,
paddingBottom: 5,
margin: 2,
},
infoText: {
textAlign: 'center',
fontSize: 16,
},
});
export default CareProviderSequenceScreen ;
CareProviderSequenceScreen .navigationOptions = () => ({
title: "Home & Personal Care",
headerTintColor: '#9EBBD7',
headerStyle: {
height: 65,
backgroundColor: '#1E5797',
shadowColor: "#000",
shadowOffset: {
width: 0,
height: 1,
},
shadowOpacity: 0.20,
shadowRadius: 1.41,
elevation: 2,}
});
First, you are assigning an object to services array.
Second, you are not accessing the query state properly. It should be
const { query } = this.state

Delete List Item on right swipe react-native

// Here I am trying to delete List item from Flat List .
Data is populating from JSON on Flat List now I have to delete particular list item data form list , for that I am using "Swipeout" . but getting error "Type error: undefined is not an object(evaluting this.2.viewNote.bind")
Please help . Where am going wrong and how can I do this
import React, { Component } from 'react';
import { View, Text, TextInput,
FooterTab,Button,TouchableOpacity, ScrollView, StyleSheet,
ActivityIndicator ,Header,FlatList} from 'react-native';
import {Icon} from 'native-base';
import { Table, Row, Rows } from 'react-native-table-component';
import { createStackNavigator } from 'react-navigation';
import { SearchBar } from 'react-native-elements';
import Swipeout from 'react-native-swipeout';
let swipeBtns = [{
text: 'Delete',
backgroundColor: 'red',
underlayColor: 'rgba(0, 0, 0, 1, 0.6)',
onPress: () => { this.deleteNote(item) }
}];
export default class OpenApplianceIssue extends Component {
constructor() {
super();
this.state = {
AbcSdata: null,
loading: true,
search: '',
tableData: [], qrData: '', selectedPriority: '',
selectedIssue: '', selectedReason: '', selectedTriedRestart: '',
selectedPowerLED: '', selectedBurning: '', selectedNoise: '',
};
this.setDate = this.setDate.bind(this);
}
setDate(newDate) {
}
_loadInitialState = async () => {
const { navigation } = this.props;
const qdata = navigation.getParam('data', 'NA').split(',');
var len = qdata.length;
const tData = [];
console.log(len);
for(let i=0; i<len; i++)
{
var data = qdata[i].split(':');
const entry = []
entry.push(`${data[0]}`);
entry.push(`${data[1]}`);
tData.push(entry);
}
this.setState({tableData: tData } );
console.log(this.state.tableData);
this.setState({loading: true});
}
componentDidMount() {
this._loadInitialState().done();
this.createViewGroup();
}
createViewGroup = async () => {
try {
const response = await fetch(
'http:/Dsenze/userapi/sensor/viewsensor',
{
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
"password": 'admin',
"username": 'admin',
"startlimit":"0",
"valuelimit":"10",
}),
}
);
const responseJson = await response.json();
const { sensorData } = responseJson;
this.setState({
AbcSdata: sensorData,
loading: false,
});
} catch (e) {
console.error(e);
}
};
updateSearch = search => {
this.setState({ search });
};
keyExtractor = ({ id }) => id.toString();
keyExtractor = ({ inventory }) => inventory.toString();
renderItem = ({ item }) => (
<Swipeout right={swipeBtns}>
<TouchableOpacity
style={styles.item}
activeOpacity={0.4}
onPress={this.viewNote.bind(this, item)} >
<Text >Id : {item.id}</Text>
<Text>Inventory : {item.inventory}</Text>
<Text>SensorType : {item.sensorType}</Text>
<Text>TypeName : {item.typeName}</Text>
</TouchableOpacity>
</Swipeout>
);
viewNote(item) {
this.props.navigator.push({
title: 'The Note',
component: ViewNote,
passProps: {
noteText: item,
noteId: this.noteId(item),
}
});
}
onClickListener = (viewId) => {
if(viewId == 'tag')
{
this.props.navigation.navigate('AddSensors');
}}
renderSeparator = () => {
return (
<View
style={{
height: 1,
width: "86%",
backgroundColor: "#CED0CE",
}}
/>
);
};
render() {
const { loading, AbcSdata } = this.state;
const state = this.state;
return (
<ScrollView>
<View style={styles.container1}>
<Button full rounded
style={{fontSize: 20, color: 'green'}}
styleDisabled={{color: 'red'}}
onPress={() => this.onClickListener('tag')}
title="Add Sensors"
>
Add Sensors
</Button>
</View>
<View style={styles.container1}>
{this.state.loading ? (
<ActivityIndicator size="large" />
) :
(
<FlatList
data={AbcSdata}
renderItem={this.renderItem}
keyExtractor={this.keyExtractor}
ItemSeparatorComponent={this.renderSeparator}
/>
)}
</View>
<View>
<Text
style={{alignSelf: 'center', fontWeight: 'bold', color: 'black'}} >
Inventory Details
</Text>
<Table borderStyle={{borderWidth: 2, borderColor: '#c8e1ff', padding:10,paddingBottom: 10}}>
<Rows data={state.tableData} textStyle={styles.text}/>
</Table>
</View>
</ScrollView>
);
}
}
const styles = StyleSheet.create(
{
container1:
{
flex: 1,
alignItems: 'stretch',
fontFamily: "vincHand",
color: 'blue'
},
header_footer_style:{
width: '100%',
height: 44,
backgroundColor: '#4169E1',
alignItems: 'center',
justifyContent: 'center',
color:'#ffffff',
},
Progressbar:{
justifyContent: 'center',
alignItems: 'center',
color: 'blue',
},
ListContainer :{
borderColor: '#48BBEC',
backgroundColor: '#000000',
color:'red',
alignSelf: 'stretch' ,
},
container2:
{
flex: 1,
justifyContent: 'center',
alignItems: 'stretch',
paddingHorizontal: 15
},
inputBox:{
width:300,
borderColor: '#48BBEC',
backgroundColor: '#F8F8FF',
borderRadius:25,
paddingHorizontal:16,
fontSize:16,
color:'#000000',
marginVertical:10,
},
button:{
width:300,
backgroundColor:'#4169E1',
borderRadius:25,
marginVertical:10,
paddingVertical:16
},
buttonText:{
fontSize:16,
fontWeight:'500',
color:'#ffffff',
textAlign:'center'
},
textStyle:{
fontSize:16,
fontWeight:'500',
color:'#ffffff',
textAlign:'center'
},
item:
{
padding: 15
},
text:
{
fontSize: 18
},
button:{
width:300,
backgroundColor:'#4169E1',
borderRadius:25,
marginVertical:10,
paddingVertical:16
},
buttonText:{
fontSize:16,
fontWeight:'500',
color:'red',
textAlign:'center'
},
separator:
{
height: 2,
backgroundColor: 'rgba(0,0,0,0.5)'
},
container: { flex: 1, padding: 16, paddingTop: 30, backgroundColor: '#fff' },
head: { height: 40, backgroundColor: '#f1f8ff' },
text: { margin: 6 }
});
Thanks .
First thing first,
Try using fat-arrow functions whenever possible, which will automatically solve your binding issues.
You will have to use the extraData= {this.state.activeRow} in your flatlist with newly added state activeRow.
I have updated your renderItem().
Check out the following updated code. Hope this helps.
import * as React from 'react';
import { View, Text, TextInput,
FooterTab, Button, TouchableOpacity, ScrollView, StyleSheet,
ActivityIndicator, Header, FlatList } from 'react-native';
import { Table, Row, Rows } from 'react-native-table-component';
import { createStackNavigator } from 'react-navigation';
import { SearchBar } from 'react-native-elements';
import { Constants } from 'expo';
// You can import from local files
import AssetExample from './components/AssetExample';
// or any pure javascript modules available in npm
import { Card } from 'react-native-paper';
import Swipeout from 'react-native-swipeout';
export default class App extends React.Component {
constructor() {
super();
this.state = {
AbcSdata: null,
loading: true,
search: '',
tableData: [], qrData: '', selectedPriority: '',
selectedIssue: '', selectedReason: '', selectedTriedRestart: '',
selectedPowerLED: '', selectedBurning: '', selectedNoise: '',
rowID:'',
activeRow: null
};
this.setDate = this.setDate.bind(this);
}
swipeBtns = [{
text: 'Delete',
type: 'delete',
backgroundColor: 'red',
underlayColor: 'rgba(0, 0, 0, 1, 0.6)',
onPress: () => {
console.log("Deleting Row with Id ", this.state.activeRow);
this.deleteNote(this.state.activeRow);
}
}];
removeItem = (items, i) =>
items.slice(0, i).concat(items.slice(i + 1, items.length));
deleteNote = (rowIndex) => {
//add your custome logic to delete the array element with index.
// this will temporary delete from the state.
let filteredData = this.removeItem(this.state.AbcSdata,rowIndex);
this.setState({AbcSdata: [] },()=> {
this.setState({AbcSdata: filteredData },()=> {console.log("Row deleted.", rowIndex)});
});
};
setDate(newDate) {
}
_loadInitialState = async () => {
const { navigation } = this.props;
const qdata = navigation.getParam('data', 'NA').split(',');
var len = qdata.length;
const tData = [];
console.log(len);
for (let i = 0; i < len; i++) {
var data = qdata[i].split(':');
const entry = []
entry.push(`${data[0]}`);
entry.push(`${data[1]}`);
tData.push(entry);
}
this.setState({ tableData: tData });
console.log(this.state.tableData);
this.setState({ loading: true });
}
componentDidMount() {
//this._loadInitialState().done();
this.createViewGroup();
}
createViewGroup = async () => {
try {
const response = await fetch(
'/Dsenze/userapi/sensor/viewsensor',
{
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
"password": 'admin',
"username": 'admin',
"startlimit": "0",
"valuelimit": "10",
}),
}
);
const responseJson = await response.json();
const { sensorData } = responseJson;
this.setState({
AbcSdata: sensorData,
loading: false,
});
} catch (e) {
console.error(e);
}
};
updateSearch = search => {
this.setState({ search });
};
keyExtractor = ({ id }) => id.toString();
keyExtractor = ({ inventory }) => inventory.toString();
onSwipeOpen(rowId, direction) {
if(typeof direction !== 'undefined'){
this.setState({activeRow:rowId});
console.log("Active Row",rowId);
}
}
renderItem = ({ item, index }) => (
<Swipeout
right={this.swipeBtns}
close={(this.state.activeRow !== index)}
rowID={index}
sectionId= {1}
autoClose = {true}
onOpen = {(secId, rowId, direction) => this.onSwipeOpen(rowId, direction)}
>
<TouchableOpacity
style={styles.item}
activeOpacity={0.4}
onPress={this.viewNote(item)} >
<Text >Id : {item.id}</Text>
<Text>Inventory : {item.inventory}</Text>
<Text>SensorType : {item.sensorType}</Text>
<Text>TypeName : {item.typeName}</Text>
</TouchableOpacity>
</Swipeout>
);
viewNote =(item) => {
this.props.navigator.push({
title: 'The Note',
component: this.ViewNote,
passProps: {
noteText: item,
noteId: this.noteId(item),
}
});
console.log("View Note Success");
}
onClickListener = (viewId) => {
if (viewId == 'tag') {
this.props.navigation.navigate('AddSensors');
}
}
renderSeparator = () => {
return (
<View
style={{
height: 1,
width: "86%",
backgroundColor: "#CED0CE",
}}
/>
);
};
render() {
const { loading, AbcSdata } = this.state;
const state = this.state;
return (
<ScrollView>
<View style={styles.container1}>
<Button full rounded
style={{ fontSize: 20, color: 'green' }}
styleDisabled={{ color: 'red' }}
onPress={() => this.onClickListener('tag')}
title="Add Sensors"
>
Add Sensors
</Button>
</View>
<View style={styles.container1}>
{this.state.loading ? (
<ActivityIndicator size="large" />
) :
(
<FlatList
data={AbcSdata}
renderItem={this.renderItem}
keyExtractor={this.keyExtractor}
extraData= {this.state.activeRow}
ItemSeparatorComponent={this.renderSeparator}
/>
)}
</View>
<View>
<Text
style={{ alignSelf: 'center', fontWeight: 'bold', color: 'black' }} >
Inventory Details
</Text>
<Table borderStyle={{ borderWidth: 2, borderColor: '#c8e1ff', padding: 10, paddingBottom: 10 }}>
<Rows data={state.tableData} textStyle={styles.text} />
</Table>
</View>
</ScrollView>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
paddingTop: Constants.statusBarHeight,
backgroundColor: '#ecf0f1',
padding: 8,
},
paragraph: {
margin: 24,
fontSize: 18,
fontWeight: 'bold',
textAlign: 'center',
},
});

Categories

Resources