nested array in Flatlist created with Redux - javascript

So I'm trying to display an array with some data in a Flatlist, I use React-Redux to update the initial State in the Reducer, I do it by collecting all data in LIST CREATION screen, and I use .push to insert them in an array, then I use updateList to update the initial State of list, and I use getDerivedStateFromProps to get that list in TRIALLIST screen and display it in a Flatlist, the problem is that I unintentionally created nested arrays, and it doesn't let me display the data in the Flatlist, this is the example of an array I'm trying to display:
Array [
Array [
Object {
"Name": Object {
"Name": "John",
},
"key": 0.05992611071666909,
"favNumber": 1,
"age": 30,
},
],
]
and here there are the various screens:
LIST CREATION
import { connect } from 'react-redux';
import { updateList } from '../../../../../redux/actions/index.js';
class trial extends Component {
constructor(props) {
super(props);
this.state = {
trial: '',
list: [],
};
}
submitTrial(){
let list = this.state.list;
list.push({
key: Math.random(),
Name: this.props.route.params,
favNum: favNum,
age: age,
});
this.props.updateList(list);
this.props.navigation.navigate("TrialList");
}
render() {
return (
<Button transparent>
<Icon
name="checkmark"
onPress={() => this.submitTrial()}
/>
</Button>
const mapDispatchToProps = { updateList };
export default connect( mapDispatchToProps )( trial );
TRIALLIST
class TrialList extends Component {
constructor(props) {
super(props);
this.state = {
list: [],
};
}
static getDerivedStateFromProps(props, state) {
if (props?.list) {
return {
list: [...state.list, props.list],
};
}
return null;
}
render() {
return (
<FlatList
data={this.state.list}
keyExtractor={(item, index) => item.key.toString()}
contentContainerStyle={{ flexGrow: 1 , flexGrow: hp('20%')}}
renderItem={({ item }) => (
<View>
<View>
<Text>
{item.Name.Name}
</Text>
<Text>
{item.favNumber}
</Text>
<Text>
{item.age}
</Text>
</View>
</View>
/>
function mapStateToProps(store){
return{
list: store.userState.list
};
}
export default connect(mapStateToProps)(TrialList);
INDEX.JS
import { ADD_LIST } from "../constants/index";
export const updateList = (list) => {
return console.log({ type: ADD_LIST, payload: list})
}
REDUCER
import { USER_STATE_CHANGE, ADD_LIST } from "../constants";
const initialState = {
currentUser: null,
list: null,
};
export const user = (state = initialState, action) => {
switch (action.type){
case USER_STATE_CHANGE:
return {
...state,
currentUser: action.currentUser,
};
case ADD_LIST:
return{
...state,
list: [...action.payload],
}
default:
return state
}
};
Thanks in advance for your help.

Related

How to prevent old array from staying displayed after refreshing and displaying updated array

Right now I'm trying to display some array values on a page. The array data is what is contained in a real-time database in Firebase. After adding to the array/entering another value into the database on the previous page, we are taken to the display page where the array values are displayed. Here is a screenshot of what is happening:
The array being rendered with the only value it has, 88
after adding 89 into the array (there should only be two values, 88 and 89, so only those two should be display, not a repeat of 88
Here's my code for DashBoard.js
import React, { useState, Component } from 'react'
import { Image, Text, TextInput, TouchableOpacity, View } from 'react-native'
import { KeyboardAwareScrollView } from 'react-native-keyboard-aware-scroll-view';
import styles from './styles';
import AsyncStorage from '#react-native-community/async-storage';
import { firebase, firebaseConfig, db, getUserDocument, realtime } from '../../firebase/config'
import "firebase/auth";
import "firebase/firestore";
import "firebase/database";
const user = firebase.auth().currentUser;
var data1 = [];
export default class DashBoard extends React.Component {
constructor(props) {
super(props);
this.state =
{
bp: '',
ag: '',
mp: '',
intVal: [],
dash: ''
};
}
componentDidMount() {
//console.log(data1);
const keys = []
const userRef = firebase.database().ref("users");
const uidRef = firebase.database().ref("users/" + firebase.auth().currentUser.uid);
const bpRef = firebase.database().ref("users/" + firebase.auth().currentUser.uid + "/" + "BloodPressure")
const path = bpRef.toString();
bpRef.push({
bpMeasure: this.state.bp,
date: Date.now(),
})
bpRef.once('value').then(snapshot => {
snapshot.forEach(item => {
var temp = { bp1: item.val().bpMeasure };
data1.push(Object.values(temp));
this.setState({ data1 })
//this.dash = temp;
this.setState({ dash: Object.values(temp) });
this.setState({ intVal: Object.values(temp) })
return false;
});
});
// DashBoard.navigationOptions = {
// headerTitle: 'Dash Board',
// headerLeft: null,
// };
}
render() {
return (
<View style={styles.MainContainer}>
<View style={styles.innerContainer}>
<Text style={styles.TextStyle}>Your Blood Pressure Records</Text>
{data1.map((d, i) => (
<Text key={i} style={styles.TextStyle}>{d}</Text>
))}
</View>
</View>
)
}
}
The previous page with the form, MoreInfo.js
import React, { useState, Component } from 'react'
import { Image, Text, TextInput, TouchableOpacity, View } from 'react-native'
import { KeyboardAwareScrollView } from 'react-native-keyboard-aware-scroll-view';
import styles from './styles';
import AsyncStorage from '#react-native-community/async-storage';
import { firebase, firebaseConfig, db, getUserDocument, realtime } from '../../firebase/config'
import "firebase/auth";
import "firebase/firestore";
import "firebase/database";
const user = firebase.auth().currentUser;
const counts = []
const trial = [];
let current = []
var data1 = [];
//const[dash, setDash] = useState('')
export default class MoreInfo extends React.Component {
constructor(props) {
super(props);
this.state =
{
bp: '',
ag: '',
mp: '',
intVal: [],
dash: ''
};
}
componentDidMount() {
this.fetchData();
db.collection("users").doc(firebase.auth().currentUser.uid).update(
{
age: this.state.ag
}
),
db.collection("users").doc(firebase.auth().currentUser.uid).update(
{
monthsPreg: this.state.mp
});
}
updateInfo = () => {
const keys = []
const userRef = firebase.database().ref("users");
const uidRef = firebase.database().ref("users/" + firebase.auth().currentUser.uid);
const bpRef = firebase.database().ref("users/" + firebase.auth().currentUser.uid + "/" + "BloodPressure")
const path = bpRef.toString();
bpRef.push({
bpMeasure: this.state.bp,
date: Date.now(),
})
db.collection("users").doc(firebase.auth().currentUser.uid).update(
{
age: this.state.ag
}
),
db.collection("users").doc(firebase.auth().currentUser.uid).update(
{
monthsPreg: this.state.mp
}
);
}
fetchData = async () => {
const userRef = firebase.database().ref("users");
const uidRef = firebase.database().ref("users/" + firebase.auth().currentUser.uid);
const bpRef = firebase.database().ref("users/" + firebase.auth().currentUser.uid + "/" + "BloodPressure");
bpRef.once('value').then(snapshot => {
snapshot.forEach(item => {
var temp = { bp1: item.val().bpMeasure };
// var temp = item.val();
data1.push(Object.values(temp));
//console.log(data1)
this.setState({ data1 })
//this.dash = temp;
this.setState({ dash: Object.values(temp) });
this.setState({ intVal: Object.values(temp) })
//console.log(this.state.dash);
return false;
});
//console.log(data1[0])
// console.log(data1);
//console.log(data1);
});
}
onPress = () => {
// navigation.navigate('Home', { user })
}
onFooterLinkPress = () => {
this.props.navigation.navigate('Home', { user })
}
onLinkPress = () => {
this.props.navigation.navigate('DashBoard', { user })
}
render() {
return (
<View style={styles.container}>
<KeyboardAwareScrollView style={{ flex: 1, width: '100%' }}
keyboardShouldPersistTaps="handled"
onPress={KeyboardAwareScrollView.dismiss}
accessible={false}
>
<Image
style={styles.logo}
source={require('../../../assets/icon.png')}
/>
<TextInput
style={styles.input}
placeholderTextColor="#aaaaaa"
secureTextEntry
placeholder='Blood Pressure'
underlineColorAndroid="transparent"
autoCapitalize="none"
multiline
onChangeText={(bp) => this.setState({ bp })}
value={`${this.state.bp}`}
/>
<TextInput
style={styles.input}
placeholderTextColor="#aaaaaa"
secureTextEntry
placeholder='Months Pregnant'
underlineColorAndroid="transparent"
autoCapitalize="none"
multiline
onChangeText={(mp) => this.setState({ mp })}
value={`${this.state.mp}`}
/>
<TextInput
style={styles.input}
placeholderTextColor="#aaaaaa"
secureTextEntry
placeholder='Age'
underlineColorAndroid="transparent"
autoCapitalize="none"
multiline
onChangeText={(ag) => this.setState({ ag })}
value={`${this.state.ag}`}
/>
<View style={styles.innerContainer}>
<TouchableOpacity
style={styles.button}
onPress=
{
//console.log(data1),
this.updateInfo
//this.getData
}
>
<Text style={styles.buttonTitle}>Submit Data</Text>
</TouchableOpacity>
</View>
<View style={styles.footerView}>
<Text onPress={this.onFooterLinkPress} style={styles.footerLink}>Home</Text>
</View>
{/* <View style={styles.footerView}>
{data1.map((d, i) => (
<Text key={i}>{d}</Text>
))}
{/* <Text style={styles.footerText}>{"Blood Pressure: "}{this.state.data1}</Text> */}
{/* </View> */}
<View style={styles.footerView}>
<Text onPress={this.onLinkPress} style={styles.footerLink}>Dashboard</Text>
</View>
</KeyboardAwareScrollView>
</View>
);
}
}
Console Response:
Console response screenshot
Object {
"bp1": "120",
}
Array []
Object {
"bp1": "",
}
Array []
Object {
"bp1": "99",
}
Array []
Object {
"bp1": "",
}
Array []
Object {
"bp1": "100",
}
Array []
Object {
"bp1": "",
}
Array []
Object {
"bp1": "",
}
Array []
After logging state
Array [
"",
]
Object {
"bp1": "",
}
Array []
Object {
"ag": "",
"bp": "",
"dash": Array [
"",
],
"data1": Array [
"",
],
"intVal": Array [
"",
],
"mp": "",
}
Update so I figured out the problem:
this.setState(prevState => ({
data1: [...prevState.data1, temp]
}))
//(temp: var temp = item.val().bpMeasure; // item is from the snapshot function)
....
render() {
console.log(this.state.data1)
return (
<View style={styles.MainContainer}>
<View style={styles.innerContainer}>
<Text style={styles.TextStyle}>Your Blood Pressure Records</Text>
{this.state.data1.map((d, i) => (
<Text key={i} style={styles.TextStyle}>{d}</Text>
))}
</View>
</View>
)
}
By doing this, I didn't repeatedly add the old values to my array and also fixed my issue of rendering the same array again and again on the dash board page.

passing data from child to parent returns undefined is not an object(evaluating 'new _reactNative.ListView.DataSource')

Am trying to pass data from one component(which is a child component) to another component(which is a parent component) using
React native ListView DataSource
which in turn return this error undefined is not an object(evaluating 'new _reactNative.ListView.DataSource')
This is the ListItem component(which is the child component)
import React, { Component } from 'react';
import { Text, TouchableWithoutFeedback } from 'react-native';
import { Icon, Container } from 'native-base';
import moment from 'moment';
class ListItem extends Component {
constructor(){
super();
this.state = {
attendance: []
};
}
attendee = [{
courseName: 'comp',
lecturer: 'Akanbi T.B',
students: 'Tunde Ajagba',
date: '10/11/2020',
},{
courseName: 'comp',
lecturer: 'Akanbi T.B',
students: 'Tunde Ajagba',
date: '09/11/2020',
},
{
courseName: 'comp',
lecturer: 'Akanbi T.B',
students: 'Tunde Ajagba',
date: '08/11/2020',
},
{
courseName: 'comp',
lecturer: 'Akanbi T.B',
students: 'Kola Babatunde',
date: '09/11/2020',
},
{
courseName: 'comp',
lecturer: 'Akanbi T.B',
students: 'Kola Babatunde',
date: '10/11/2020',
}
];
onRowPress() {
this.record = this.attendee.map(function(item,index) {
alert("item: " + item.courseName + " at index: " + index );
});
//const { navigate } = this.props.navigation;
//navigate('attendanceDetails', { record });
}
render() {
return (
<TouchableWithoutFeedback onPress={this.onRowPress.bind(this)}>
<Container style={styles.containerStyle}>
<Text style={styles.labelStyle}>Course:</Text>
<Text style={styles.titleStyle}>{courseName}</Text>
<Text style={styles.labelStyle}>Date:</Text>
<Text style={styles.titleStyle}>
</Text>
<form onSubmit = {this.onTrigger}>
<input type = "submit" value = "Submit"/>
</form>
<Icon name='ios-arrow-forward' style={{ color: 'grey', marginLeft: 5 }} />
</Container>
</TouchableWithoutFeedback>
);
}
}
export default ListItem;
now, I know there is an error in the onRowPress function as am unable to bring the array to work i the render function(this, I don't know how to do it).
Meanwhile, in the
ViewAttendance component(which is the parent component).
This is what I have
import _ from 'lodash';
import React, { Component } from 'react';
import { ListView, ScrollView } from 'react-native';
import { Container } from 'native-base';
import AsyncStorage from '#react-native-community/async-storage';
import ListItem from './ListItem';
export default class ViewAttendance extends Component {
constructor(props){
super(props);
}
componentWillMount() {
const { lecturer } = "Akanbi T.B";//this.props.route.params;
this.createDataSource(this.props);
}
componentWillReceiveProps(nextProps) {
this.createDataSource(nextProps);
}
createDataSource({ records }) {
const ds = new ListView.DataSource({
rowHasChanged: (r1, r2) => r1 !== r2
});
const items = _.map(records, (val, key) => {
return { ...val, key };
});
this.dataSource = ds.cloneWithRows(items);
}
renderRow(record, navigation) {
return (
<ListItem record={record} navigation={navigation} />
);
}
render() {
const { navigation } = 'a';//this.props.route.params;
return (
<Container style={styles.containerStyle}>
<ListView
enableEmptySections
dataSource={this.dataSource}
renderRow={(record) => this.renderRow(record, navigation)}
/>
</Container>
);
}
}
};
How do I solve the issues at hand?

React Native Run Child Reference Method From Another Component

I am trying to run a component method of another component. I am trying this using react ref. I am also following this link:
https://medium.freecodecamp.org/react-changing-state-of-child-component-from-parent-8ab547436271 But my structure is a bit more complicated.
List.js
class List extends Component {
constructor(){
super()
this.LoadCounterElement = React.createRef()
}
render(){
return(
<View>
<ItemGenerator />
<LoadCounter ref={this.LoadCounterElement}/>
</View>
)
}
}
function mapStateToProps(state) {
return {
counter: state.counter.counter
}
}
function mapDispatchToProps(dispatch) {
return {
increaseCounter: () => dispatch({ type: 'INCREASE_COUNTER' }),
decreaseCounter: () => dispatch({ type: 'DECREASE_COUNTER' }),
}
}
export default connect(mapStateToProps)(List);
ItemGenerator.js
class ItemGenerator extends Component {
render() {
return (
<ScrollView>
{
this.state.data.map((item, index) => {
return(<ItemList navigate={this.props.navigate} data={item} key={index}/>)
})
}
</ScrollView>
)
}
}
LoadCounter.js
class LoadCounter extends Component {
constructor(props) {
super(props)
this.state = {
count : 0,
}
}
componentDidMount() {
this._renderCount()
}
_renderCount = () => {
this.setState({count:this.props.counter})
}
render(){
return(
<View>
<Text>{this.state.count}</Text>
</View>
)
}
}
function mapStateToProps(state) {
return {
counter: state.counter.counter
}
}
export default connect(mapStateToProps)(withNavigation(LoadCounter));
ItemList.js
class ItemList extends Component {
render() {
return(
<View>
<TouchableOpacity onPress={() => {
this.props.increaseCounter()
this.LoadCounterElement.current._renderCount()
}}>
<Card containerStyle={{margin: 0}}>
<View style={{flex:1, flexDirection:'row', height:70, alignItems:'center', justifyContent:'space-between'}}>
<View style={{flexDirection:'row', alignItems:'center', width:'55%'}}>
<View style={{flexDirection:'column', marginLeft:10}}>
<Text style={{...}}>{this.props.data.name}</Text>
</View>
</View>
</View>
</Card>
</TouchableOpacity>
</View>
)
}
}
function mapDispatchToProps(dispatch) {
return {
increaseCounter: () => dispatch({ type: 'INCREASE_COUNTER' }),
decreaseCounter: () => dispatch({ type: 'DECREASE_COUNTER' }),
}
}
export default connect(mapStateToProps)(ItemList);
counterReducer.js
const initialState = {
counter: 1
}
const counterReducer = (state = initialState, action) => {
switch (action.type) {
case 'INCREASE_COUNTER':
return { counter: state.counter + 1 }
case 'DECREASE_COUNTER':
return { counter: state.counter - 1 }
}
return state
}
export default counterReducer;
As you can see in ItemLiist Component, i am trying to run _renderCount method which is in Component LoadCounter. But its not working. Kindly guide what i am missing?
The problem here is that you have some data in child component that should be reflected in a parent component. I would recommend that you move the shared state in the parent component or to the reducer state.
It is odd that you are using an action creator to increment/decrement counts - which I am thinking that updates some reducer state. If this is the case, why store that state in the local component state again ? You could just read the counter state from the reducer in your parent component.
Parent.js
class Parent extends React.Component {
render() {
return (
<div>
<span>{this.props.count}</span>
</div>
);
}
}
const mapStateToProps = state => ({
count: state.yourCountReducer.count,
});
export default connect(mapStateToProps)(Parent);
Child.js
class Child extends React.Component {
render() {
return (
<div>
<button onClick={() => this.props.increaseCounter()}>+</button>
<button onClick={() => this.props.decreaseCounter()}>-</button>
</div>
);
}
}
const mapDispatchToProps = dispatch => ({
increaseCounter: () => dispatch({ type: 'INCREASE_COUNTER' }),
decreaseCounter: () => dispatch({ type: 'DECREASE_COUNTER' }),
});
export default connect(null, mapDispatchToProps)(Child);
This way, the parent component will show the updated counter state when the child component updates the count. From your sample code, I am not sure if there is any good reason to store a shared reducer state in any component's local state.

React Native - Modal with Flatlist items

I'm making a modal that will popup when the user clicks a flatlist button or items, and there the user will see the details about the item he/she clicks. Basically, I want to pass the items of flatlist to modal.
I'm actually done with the popup of the modal, now I have to show the details like menu description and menu price. I've found a post here in stackoverflow and I follow everything in there but I am having an error regarding with an " id ", and I can't figure out how to fix it.
Here is my code
Details.js
import React, {Component} from 'react';
import {Text, TouchableHighlight, View,
StyleSheet, Platform, FlatList, AppRegistry,
TouchableOpacity, RefreshControl, Dimensions, Modal, TextInput, TouchableWithoutFeedback, Keyboard
} from 'react-native';
import AddModal from '../Modal/AddModal';
var screen = Dimensions.get('window');
const DismissKeyboard = ({ children }) => (
<TouchableWithoutFeedback onPress = {() => Keyboard.dismiss()}>
{children}
</TouchableWithoutFeedback>
);
export default class Details extends Component {
static navigationOptions = {
title: ''
};
constructor()
{
super ()
this.state = {
data: [],
showModal: false,
id: null,
}
}
fetchData = async() => {
const { params } = this.props.navigation.state;
const response_Cat = await fetch('http://192.168.254.101:3307/categories/' + params.id);
const category_Cat = await response_Cat.json();
this.setState({data: category_Cat});
};
componentDidMount() {
this.fetchData();
};
_onRefresh() {
this.setState({ refreshing: true });
this.fetchData().then(() => {
this.setState({ refreshing: false })
});
};
_onPressItem(id) {
this.setState({
modalVisible: true,
id: id
});
}
_renderItem = ({item}) => {
return (
<TouchableHighlight
id = { item.menu_desc }
onPress = { this._onPressItem(item.menu_desc) }
>
<View>
<Text>{ this.state.id }</Text>
</View>
</TouchableHighlight>
)
};
render() {
const { params } = this.props.navigation.state;
return (
<View style = { styles.container }>
<AddModal
modalVisible = { this.state.modalVisible }
setModalVisible = { (vis) => { this.setModalVisible(vis) }}
id = { this.state.id }
/>
<FlatList
data = { this.state.data }
renderItem = { this._renderItem }
keyExtractor={(item, index) => index}
/*refreshControl = {
<RefreshControl
refreshing = { this.state.refreshing }
onRefresh = { this._onRefresh.bind(this) }
/>
}*/
/>
</View>
);
}
}
const styles = StyleSheet.create({
...
})
//AppRegistry.registerComponent('Details', () => Details);
AddModal.js
import React, {Component} from 'react';
import {Text, TouchableHighlight, View,
StyleSheet, Platform, FlatList, AppRegistry,
TouchableOpacity, RefreshControl, Dimensions, TextInput, Modal
} from 'react-native';
export default class AddModal extends Component {
constructor(props) {
super(props);
this.state = {
showModal: false,
id: null
};
}
componentWillReceiveProps(nextProps) {
this.setState({
showModal: nextProps.showModal,
id: nextProps.id,
})
}
render() {
return (
<Modal
animationType="slide"
transparent={ true }
visible={ this.state.modalVisible }
onRequestClose={() => { this.props.setModalVisible(false) }}>
<View>
<View>
<Text>{ this.state.id }</Text>
<TouchableHighlight
onPress = {() => { this.props.setModalVisible(false) }}
>
<Text>Hide Modal</Text>
</TouchableHighlight>
</View>
</View>
</Modal>
)
}
}
Just wanted to pointout an issue in your code (not related to 'id' error, id error already answer by digit). In the renderItem function, you are calling onPress = { this._onPressItem(item.menu_desc) }, it should be changed to
onPress = { () => this._onPressItem(item.menu_desc) }
I guess, you will call the onPressItem when user click on list item.
EDIT:
I have made a couple of changes to make your code working. Here are the changes.
In your AppModal.js, you are setting modal visibility in showModal: nextProps.showModal , but in the <Modal ...> you have set visible
= { this.state.modalVisible }. Also in Details.js you have written <AddModal modalVisible ...>.
First I changed showModal to modalVisible in Details.js and in AppModal.js.
Details.js
constructor()
{
super ()
this.state = {
data: [],
modalVisible: false,
id: null,
}
}
Then I changed _onPressItem(id) to _onPressItem = (id)
Made changes in renderItem as
<TouchableHighlight
id = { item.enName }
onPress = { () => this._onPressItem(item.enName) }
>
in render function I have set modal visibility as
<AddModal
...
setModalVisible = { (vis) => { this.setState({
modalVisible: vis
})
}}
...
/>
AppModal.js
Changed showModal to modalVisible
constructor(props) {
super(props);
this.state = {
modalVisible: props.modalVisible,
d: null
};
}
componentWillReceiveProps(nextProps) {
this.setState({
modalVisible: nextProps.modalVisible,
id: nextProps.id,
})
}
In the constructor, I have added modalVisible: props.modalVisible.
Hope this will help!
I guess item.menu_desc is an id of each item so it must be {item.menu_desc} not {id}. Change it like below
_renderItem = ({item}) => {
return (
<TouchableHighlight
id = { item.menu_desc }
onPress = { this._onPressItem(item.menu_desc) }
>
<View>
<Text>{ item.menu_desc }</Text>
</View>
</TouchableHighlight>
)
};

React Native Flatlist returns the wrong number of empty rows

When I run the code below, it displays 3 empty rows. It should be showing two rows each with a color and enddate and I want to use the 'Parent' as the unique key. The 'Parent' is the unique key created by Firebase when color and enddate were pushed to Firebase with '.push'.
I've tried all sorts of things to get it to display. I did get content to display when I made the 'renderItems' return 'this.state.list', but that returned 3 lines all with the same data, which is the content of the last array on the console log.
I would really appreciate some help to get this working.
Here is the code, a copy of Firebase database and the console.log. Please note that the Firebase 'goal' has been changed to 'color'.
import React, { Component } from 'react';
import { Text, FlatList, View, Image } 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 = {
list: [],
};
}
componentDidMount() {
const { currentUser } = firebase.auth();
const Parent = firebase.database().ref(`/users/${currentUser.uid}/Profile`);
Parent.on(('child_added'), snapshot => {
this.setState({ list: [snapshot.key, snapshot.val().color, snapshot.val().enddate] });
console.log(this.state.list);
});
}
keyExtractor = (item, index) => index;
render() {
return (
<Card>
<View style={{ flex: 1 }}>
<FlatList
data={this.state.list}
keyExtractor={this.keyExtractor}
extraData={this.state}
renderItem={({ item }) => (
<Text style={styles.listStyle}>
{ item.color }
{ item.enddate }
</Text>
)}
/>
</View>
<CardSection>
<Button
style={{
flex: 1,
flexDirection: 'row'
}}
onPress={() => this.props.navigation.navigate('NextPage', { name: 'user' })}
title="Go to next page"
>
Go to next page
</Button>
</CardSection>
</Card>
);
}
}
export { List };
This is the correct way to store the list
componentDidMount() {
const { currentUser } = firebase.auth();
const Parent = firebase.database().ref(`/users/${currentUser.uid}/Profile`);
Parent.on(('child_added'), snapshot => {
const newChild = {
key: snapshot.key,
color: snapshot.val().color,
enddate: snapshot.val().enddate
}
this.setState((prevState) => ({ list: [...prevState.list, newChild] }));
console.log(this.state.list);
});
}
and your keyExtractor
keyExtractor = (item, index) => item.key;

Categories

Resources