Function not being passed to child component - javascript

I am a learner in react native, any help will go a great mile :), I started using react-navigation for my app, I have a child component as the header of my parent component, This child component contains a <TextInput/> I want to update the parent component on change of the child component's TextInput, normally passing down a function as the value of the props will work, But since I am using static navigationOptions to access the child component, that won't work, I have to set the navigation.params.state, I have done this, I have read through documentations, I looked through this link https://github.com/react-navigation/react-navigation/issues/147 But it always comes back with this error undefined is not an object(evaluating 'params.update')
Please how can I make this work and pass the function successfully to the Box component
BOX COMPONENT
class Box extends React.Component {
constructor(props) {
super(props);
this.state = {
search: ""
}
}
handleChange = (e) => {
this.props.onUpdate(e.target.value);
this.setState({search: e.target.value});
}
render() {
return (
<TextInput placeholder="Search for your herbs by name,type..." value={this.state.search}
onChange={this.handleChange}
underlineColorAndroid={'transparent'}
style={BackStyles.textBox}/> ); }}
HOME COMPONENT
export default class Home extends React.Component {
onUpdate = (val) => {
this.setState({
search: val
});
let db = SQLite.openDatabase({
name: 'test.db',
createFromLocation: "~Herbo.db",
location: 'Library'
}, this.openCB, this.errorCB);
db.transaction((tx) => {
tx.executeSql("SELECT * FROM data where name like '" + this.state.search + "' ", [], (tx, results) => {
console.log("Query completed");
var len = results.rows.length;
for (let i = 0; i < len; i++) {
let row = results.rows.item(i);
this.setState(prevState => ({
record: [...prevState.record, row],
pressed: [...prevState.pressed, false]
}));
console.log(`Record: ${row.name}`);
//this.sleep(2);
//this.setState({record: row});
}
this.setState({loader: false})
});
});
};
static navigationOptions = ({navigation}) => {
const {params} = navigation.state.params || {};
return {
headerTitle: <Box onUpdate={params.update}/>,
};
// header: null
};
componentDidMount() {
this.navigation.setParams({
update: this.props.onUpdate()
})
}
constructor(props) {
super(props);
this.state = {
record: [],
header: null,
loader: true,
pressed: {},
ar: [],
search: ''
};
let db = SQLite.openDatabase({
name: 'test.db',
createFromLocation: "~Herbo.db",
location: 'Library'
}, this.openCB, this.errorCB);
db.transaction((tx) => {
tx.executeSql('SELECT * FROM data', [], (tx, results) => {
console.log("Query completed");
var len = results.rows.length;
for (let i = 0; i < len; i++) {
let row = results.rows.item(i);
this.setState(prevState => ({
record: [...prevState.record, row],
pressed: [...prevState.pressed, false]
}));
console.log(`Record: ${row.name}`);
//this.sleep(2);
//this.setState({record: row});
}
this.setState({loader: false})
});
});
}
handlePressedIn = (i, value) => {
if (this.state.ar.length > 0) {
this.state.ar.map((value) => {
this.setState(prevState => {
const pressed = {...prevState.pressed};
pressed[value] = false;
return {pressed};
})
});
}
this.setState(prevState => {
if (!this.state.ar.includes(i)) {
this.setState(prevState => ({
ar: [...prevState.ar, i]
}));
}
const pressed = {...prevState.pressed};
pressed[i] = !pressed[i];
return {pressed};
});
this.props.navigation.navigate('Details', {
itemId: i + 1,
otherParam: value
});
};
errorCB(err) {
console.log("SQL Error: " + err);
}
successCB() {
console.log("SQL executed fine");
}
openCB() {
console.log("Database OPENED");
}
render() {
const herbs = this.state.record.map((herb) =>
<TouchableNativeFeedback onPress={() => this.handlePressedIn(herb.id - 1, herb.name)} key={herb.id}>
<View style={this.state.pressed[herb.id - 1] ? BackStyles.herbBox : BackStyles.herb_box}>
<Image style={BackStyles.image} source={{uri: `${herb.name.replace(/ /g, '')}`}}/>
<View style={{flexDirection: 'column',}}><Text
style={this.state.pressed[herb.id - 1] ? BackStyles.header2 : BackStyles.header}>{herb.name}</Text>
<Text
style={this.state.pressed[herb.id - 1] ? BackStyles.sub2 : BackStyles.sub}>{herb.bot}</Text></View>
</View></TouchableNativeFeedback>
);
const view = <ScrollView overScrollMode={'never'}>{herbs}</ScrollView>;
return (
<View style={BackStyles.main}>
<View style={{flex: 1}}>
{
this.state.loader ?
<ActivityIndicator animating={this.state.loader} color='#28B564' size="large"
style={BackStyles.activityIndicator}/> : <View>{view}</View>
} </View></View> ); }}
APP.js(Main Component)
import Splash from './components/Splash';
import {createStackNavigator} from 'react-navigation';
const RootStack = createStackNavigator(
{
Home: {
screen: Home,
},
Details: {
screen: Details,
},
},
{
initialRouteName: 'Home',
navigationOptions: {
headerStyle: {
backgroundColor: '#fff',
},
headerTintColor: '#28B564',
headerTitleStyle: {
fontWeight: 'bold',
},
},
}
);
export default class App extends Component {
constructor(props) {
super(props);
this.state = {
timePassed: false,
};
}
render() {
setTimeout(() => {
this.setState({timePassed: true})
}, 4000);
if (!this.state.timePassed) {
return <View style={{flex: 1}}>
<StatusBar backgroundColor='#28B564' barStyle='light-content'/><Splash/></View>;
} else {
return (<View style={{flex: 1}}>
<StatusBar backgroundColor='#28B564' barStyle='light-content'/>
<RootStack/></View>
);} }}

Related

ReferenceError: Can't find variable: state

I'm recording an app that records exercise logs.
If I click on the area,
I'd like to have items that correspond to that area on the screen.
import React, { Component } from "react";
import {
TouchableOpacity,
StyleSheet,
Text,
View,
FlatList,
} from "react-native";
let clickmenu = "";
class TouchableText extends Component {
render() {
clickmenu = this.props.children.item;
return (
<TouchableOpacity style={styles.text} onPress={this.props.press}>
<Text style={styles.text}>{this.props.children.item.toString()}</Text>
</TouchableOpacity>
);
}
}
class Detail extends Component {
state = {
data: {
chest: [
"플랫 벤치프레스",
"인클라인 벤치프레스",
"케이블 크로스오버",
"푸쉬업",
"딥스",
],
back: ["바벨로우", "데드리프트", "턱걸이", "씨티드 로우", "렛풀 다운"],
},
menu: [
"chest",
"back",
"legs",
"shoulder",
"biceps",
"triceps",
"abs",
"etc..",
],
isclicked: true,
};
press = () => {
this.setState({
isclicked: false,
});
};
render() {
const { data, menu, isclicked } = this.state;
return isclicked ? (
<View style={styles.container}>
<FlatList
data={this.state.menu.map((mp) => {
return mp;
})}
renderItem={(item) => (
<TouchableText press={this.press}>{item}</TouchableText>
)}
/>
</View>
) : (
<View>
{" "}
{(function () {
console.log(this);
if (clickmenu == "가슴") {
<FlatList
data={this.state.data.가슴.map((mp) => {
return mp;
})}
renderItem={(item) => <TouchableText>{item}</TouchableText>}
keyExtractor={(item, index) => index.toString()}
/>;
} else if (state.clickmenu == "등") {
<FlatList
data={this.state.data.등.map((mp) => {
return mp;
})}
renderItem={(item) => <TouchableText>{item}</TouchableText>}
/>;
} else {
console.log("world");
}
})()}
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: "black",
},
text: { flex: 1, backgroundColor: "white", fontSize: 36, color: "black" },
});
export default Detail;
If I click on the chest button, The following error occurs:
function(){if(){}}
Does this mean class detail in ? How should I solve this?
You are missing a this.
Change
} else if (state.clickmenu == "등") {
to
} else if (this.state.clickmenu == "등") {
You need to set up a constructor with your state attributes within it as such:
class Detail extends Component {
constructor(props) {
super(props);
this.state = {
isLoading: true,
stateAttributesHere: "",
};
}
...
...
}
else if (state.clickmenu == "등") => else if (clickmenu == "등")

How to scan one barcode per time? [react-native-camera]

Actually i'm new to React and i'm trying to make a simple barcode scanner which show the scanned barcode in an alert and after pressing "OK" in the alert the user should be able to scan another barcode.
The issue is that the barcode is continuously scanned and when the alert is up it's hiding and showing every second the alert.
I was trying to do something like this to show the alert only once and if OK is pressed to be able to show again the alert but only in case the OK is pressed but that had no effect..
onBarCodeRead = (e) => {
if(!this.alertPresent){
this.alertPresent = true;
Alert.alert(
"Barcode type is " + e.type,
"Barcode value is " + e.data,
[
{text: 'OK', onPress: () => this.alertPresent = false;},
],
{cancelable: false},
);
}
}
Here is full code of Barcode.JS
import React, { Component } from 'react';
import { Button, Text, View,Alert } from 'react-native';
import { RNCamera } from 'react-native-camera';
import BarcodeMask from 'react-native-barcode-mask';
class ProductScanRNCamera extends Component {
constructor(props) {
super(props);
this.camera = null;
this.barcodeCodes = [];
this.alertPresent = false;
this.state = {
camera: {
flashMode: RNCamera.Constants.FlashMode.auto,
}
};
}
onBarCodeRead = (e) => {
if(!this.alertPresent){
this.alertPresent = true;
Alert.alert(
"Barcode type is " + e.type,
"Barcode value is " + e.data,
[
{text: 'OK', onPress: () => this.alertPresent = false;},
],
{cancelable: false},
);
}
}
pendingView() {
return (
<View
style={{
flex: 1,
backgroundColor: 'lightgreen',
justifyContent: 'center',
alignItems: 'center',
}}
>
<Text>Waiting</Text>
</View>
);
}
render() {
return (
<View style={styles.container}>
<RNCamera
ref={ref => {
this.camera = ref;
}}
defaultTouchToFocus
flashMode={this.state.camera.flashMode}
mirrorImage={false}
onBarCodeRead={this.onBarCodeRead.bind(this)}
onFocusChanged={() => {}}
onZoomChanged={() => {}}
style={styles.preview}
>
<BarcodeMask/>
</RNCamera>
</View>
);
}
}
The trick here is to modify barcodeTypes props with an internal state.
const defaultBarcodeTypes = [// should be all Types from RNCamera.Constants.BarCodeType];
class ProductScanRNCamera extends Component {
state = {
// your other states
barcodeType: '',
barcodeValue: '',
isBarcodeRead: false // default to false
}
onBarcodeRead(event) {
this.setState({isBarcodeRead: true, barcodeType: event.type, barcodeValue: event.data});
}
// run CDU life-cycle hook and check isBarcodeRead state
// Alert is a side-effect and should be handled as such.
componentDidUpdate() {
const {isBarcodeRead, barcodeType, barcodeValue} = this.state;
if (isBarcodeRead) {
Alert.alert(barcodeType, barcodeValue, [
{
text: 'OK',
onPress: () => {
// Reset everything
this.setState({isBarcodeRead: false, barcodeType: '', barcodeValue: ''})
}
}
]);
}
}
render() {
const {isBarcodeRead} = this.state;
return (
<RNCamera {...your other props} barcodeTypes={isBarcodeRead ? [] : defaultBarcodeTypes}>
<BarcodeMask />
</RNCamera>
)
}
}
A hook version is cleaner
const ProductScanRNCamera = () => {
const [isBarcodeRead, setIsBarcodeRead] = useState(false);
const [barcodeType, setBarcodeType] = useState('');
const [barcodeValue, setBarcodeValue] = useState('');
useEffect(() => {
if (isBarcodeRead) {
Alert.alert(
barcodeType,
barcodeValue,
[
{
text: 'OK',
onPress: () => {
// reset everything
setIsBarcodeRead(false);
setBarcodeType('');
setBarcodeValue('');
}
}
]
);
}
}, [isBarcodeRead, barcodeType, barcodeValue]);
const onBarcodeRead = event => {
if (!isBarcodeRead) {
setIsBarcodeRead(true);
setBarcodeType(event.type);
setBarcodeValue(event.data);
}
}
return (
<RNCamera {...your props}
onBarCodeRead={onBarcodeRead}
barcodeTypes={isBarcodeRead ? [] : defaultBarcodeTypes}>
<BarcodeMask />
</RNCamera>
)
}
use setState in order to set state of component.setState will take the object and update the state of component
check code below
import React, { Component } from 'react';
import { Button, Text, View, Alert } from 'react-native';
import { RNCamera } from 'react-native-camera';
import BarcodeMask from 'react-native-barcode-mask';
class ProductScanRNCamera extends Component {
constructor(props) {
super(props);
this.camera = null;
this.barcodeCodes = [];
this.showAlert = true;
this.state = {
camera: {
flashMode: RNCamera.Constants.FlashMode.auto,
}
};
}
onBarCodeRead = (e) => {
if (this.state.alertPresent) {
this.setState({ showAlert: false });
Alert.alert(
"Barcode type is " + e.type,
"Barcode value is " + e.data,
[
{ text: 'OK', onPress: () =>console.log('ok') },
],
{ cancelable: false },
);
}
}
pendingView() {
return (
<View
style={{
flex: 1,
backgroundColor: 'lightgreen',
justifyContent: 'center',
alignItems: 'center',
}}
>
<Text>Waiting</Text>
</View>
);
}
render() {
return (
<View style={styles.container}>
<RNCamera
ref={ref => {
this.camera = ref;
}}
defaultTouchToFocus
flashMode={this.state.camera.flashMode}
mirrorImage={false}
onBarCodeRead={this.onBarCodeRead.bind(this)}
onFocusChanged={() => { }}
onZoomChanged={() => { }}
style={styles.preview}
>
<BarcodeMask />
</RNCamera>
</View>
);
}
}

Camera roll function getting duplicate images

I am using camera roll for react native to get the images on my mobile device, I used first: 1, after the camera roll function runs it stores the end_cursor from the data and uses the it in the subsequent camera roll requests as the after variable, i.e
CameraRoll.getPhotos({
first: 1,
assetType: 'Photos',
after: end_cursor
})
I then run a function when the end of the flatlist is gotten too, to load more images based on the end_cursor variable.
The images keep coming twice, there are duplicate images in the state i.e [image 1,image 1, image 2, image 2, ....], what may be causing this error, This is my full code below
constructor(props) {
super(props);
this.state = {
photos: [],
lastCursor: null,
noMorePhotos: false,
loadingMore: false,
};
}
tryPhotoLoad() {
if (!this.state.loadingMore) {
this.setState({ loadingMore: true }, () => { this.loadPhotos(); });
}
}
loadPhotos() {
const fetchParams = {
first: 1,
assetType: 'Photos',
};
if (this.state.lastCursor) {
// console.log("last cursor "+this.state.lastCursor)
fetchParams.after = this.state.lastCursor;
}
CameraRoll.getPhotos(fetchParams).then((data) => {
this.appendAssets(data);
}).catch((e) => {
// console.log(JSON.stringify(e));
});
}
appendAssets(data) {
console.log("\n"+"\n"+"\n"+JSON.stringify(data)+"\n"+"\n"+"\n")
const assets = data.edges;
const nextState = {
loadingMore: false,
};
if (!data.page_info.has_next_page) {
nextState.noMorePhotos = true;
}
if (assets.length > 0) {
this.setState({lastCursor: data.page_info.end_cursor})
// nextState.lastCursor = data.page_info.end_cursor;
let len = assets.length;
// console.log(len);
for (let i = 0; i < len; i++) {
let row = assets[i];
// console.log(row);
this.setState(prevState => ({
photos: [...prevState.photos, row]
}));
}
}
// console.log("\n"+"\n"+"\n"+JSON.stringify(nextState)+"\n"+"\n"+"\n");
this.setState(nextState);
}
endReached() {
if (!this.state.noMorePhotos) {
this.tryPhotoLoad();
}
}
componentDidMount(){
this.tryPhotoLoad();
}
render() {
const images =(
<FlatList
data={this.state.photos}
numColumns={4}
renderItem={({ item, index }) => (
<View style={{width: '25%',
height: height}}>
<Image
key={index}
resizeMode={'cover'}
style={{
flex: 1
}}
source={{ uri: item.node.image.uri }}
/></View>
)}
keyExtractor={(item, index) => `list-item-${index}`}
onEndReached={this.endReached()}
onEndReachedThreshold={0}
/>
);
return (
<View
style={{ flex: 1, backgroundColor: "#DDDBC7", flexDirection: "column" }}
>
<ScrollView>
{images}
</ScrollView>
);
}

How to delete particular list item locally and from server after swipe in react native

// Here in my code am calling 2 APIS 1.( createViewGroup = async () =>)one for get data from server and set on FlatList , id,sensorType inventory,
2 second api ("SensorDelt = (rowIndex) => ") am calling for delete particular list iteam from server ,I mean after touching particular list item , i am taking id no and that id ({"password":"admin","username":"admin","sensorid":"here i have to send id no"})am sending to server and that id will be delete .
In my code am using Swipeout delete button to delete list item ,but it is working locally, not deleting from server .
Please help
import * as React from "react";
import {
View,
Text,
TextInput,
FooterTab,
Button,
TouchableOpacity,
ScrollView,
StyleSheet,
ActivityIndicator,
Header,
Alert,
AsyncStorage,
FlatList
} from "react-native";
import { Table, Row, Rows } from "react-native-table-component";
import { createStackNavigator, createAppContainer } from "react-navigation";
import { SearchBar } from "react-native-elements";
// 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";
class OpenApplianceIssue 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);
this.onClickListener("del");
}
}
//onPress:() => this.onClickListener('tag')}
}
];
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 });
};
// Delete Sensors ********************
SensorDelt = rowIndex => {
//const Sensorid_Data = this.props.navigation.state.params.item.id;
let filteredData = this.removeItem(this.state.AbcSdata, rowIndex);
let ABHI = filteredData//const Sensorid_Data = this.state.rowIndex;
.console
.log("Value Abhi" + filteredData);
Alert.alert("Value" + filteredData);
fetch("http:/Dsenze/userapi/sensor/delsensor", {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify({
password: "admin",
username: "admin",
sensorid: filteredData
})
})
.then(response => {
//console.log(response);
return response.json();
})
.then(res => {
if (res.success == "true") {
Alert.alert("Sensor Added");
this.props.navigation.replace("OpenApplianceIssue");
} else {
Alert.alert("Success false");
}
});
};
handleValueChange(SensortypeId) {
this.setState({ SensortypeId });
}
// Delete sensors ***********************
onClickListener = viewId => {
if (viewId == "tag") {
this.props.navigation.navigate("AddSensors");
} else if (viewId == "del") {
//this.props.navigation.navigate('AddSensors');
this.SensorDelt();
}
};
componentDidMount() {
//this._loadInitialState().done();
this.createViewGroup();
}
// Get Sensor list ********************************************
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);
}
};
clickedItemText(OpenApplianceIssue) {
this.props.navigation.navigate("Item007", { item: OpenApplianceIssue });
//Abc = this.props.navigation.state.params.item.id;
}
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
style={styles.SwipeBG}
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.clickedItemText(item);
}}
>
{/* //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");
// }
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
style={styles.ListDATA}
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>
);
}
}
export default (OpenApplianceIssue = createStackNavigator({
Item007: { screen: OpenApplianceIssue }
}));
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: "center",
backgroundColor: "#ecf0f1",
padding: 8
},
paragraph: {
margin: 24,
fontSize: 18,
fontWeight: "bold",
textAlign: "center"
},
SwipeBG: {
backgroundColor: "#ffffff",
marginLeft: 7,
marginTop: 3
},
ListDATA: {
backgroundColor: "#ffffff",
marginLeft: 5,
marginTop: 3
}
});
Thanks

How to have multiple Flatlists with filtered data in React Native

How do I create multiple Flatlists that only present data with one type of 'status'?
For example:
One Flatlist for status === 'inProgress'
One Flatlist for status ===
'Done'
One Flatlist for status ===
'Failed'
All data is in the array ‘goallist’, which comes from a Firebase database.
I would really appreciate your help with this.
import React, { Component } from 'react';
import { Text, FlatList, View, Image, TouchableOpacity, Alert } from 'react-native';
import firebase from 'firebase';
import { Button, Card, CardSection } from '../common';
import styles from '../Styles';
class List extends Component {
static navigationOptions = {
title: 'List',
}
constructor(props) {
super(props);
this.state = {
goallist: '',
loading: false,
};
}
componentDidMount() {
this.setState({ loading: true });
const { currentUser } = firebase.auth();
const keyParent = firebase.database().ref(`/users/${currentUser.uid}/goalProfile`);
keyParent.on(('child_added'), snapshot => {
const newChild = {
key: snapshot.key,
goal: snapshot.val().goal,
status: snapshot.val().status
};
this.setState((prevState) => ({ goallist: [...prevState.goallist, newChild] }));
console.log(this.state.goallist);
});
this.setState({ loading: false });
}
onRenderItem = ({ item }) => (
<TouchableOpacity onPress={this.showAlert}>
<Text style={styles.listStyle}>
{ item.goal } { item.key }
</Text>
</TouchableOpacity>
);
showAlert = () => {
Alert.alert(
'Did you succeed or fail?',
'Update your status',
[
{ text: 'Completed?',
onPress: () => console.log('Completed Pressed'), },
{ text: 'Failed?',
onPress: () => console.log('Failed Pressed'),
},
{ text: 'Cancel',
onPress: () => console.log('Cancel Pressed'),
style: 'cancel' },
],
{ cancelable: false }
);
}
keyExtractor = (item) => item.key;
render() {
return (
<Card>
<View style={{ flex: 1 }}>
<FlatList
data={this.state.goallist}
keyExtractor={this.keyExtractor}
extraData={this.state}
renderItem={this.onRenderItem}
/>
</View>
</Card>
);
}
}
export { List };
You just need to modify your onRenderItem function to render some specific objects as below (this Flatlist shows only inProgress objects):
onRenderItem = ({ item }) => {
if (item.type === 'inProgress') {
return (
<TouchableOpacity onPress={this.showAlert}>
<Text style={styles.listStyle}>
{ item.goal } { item.key }
</Text>
</TouchableOpacity>
)
} else { return null; }
};

Categories

Resources