I have problem with map my array about curriences.
so as u see there is a curriences array with strings. Im using Picker to choose some between them and I have function what is included to onValueChange prop in Picker, and then comes my problem with selecting an item from picker.
Firstly I can choose a whatever item from picker, but when I want to choose again I have just this choosed item before in the list:
then i choosed for example EUR. When I want to choose a item again I have just this:
Also when I change first picker item - it changes also in the second picker... don't know why.
also adding whole code here:
import React, {Component} from 'react';
import {View, Text, TextInput, Picker} from 'react-native';
class CurrencyCashScreen extends React.Component {
state = {
currencies: ['USD', 'AUD', 'SGD', 'PHP', 'EUR'],
base: 'PLN',
amount: '',
convertTo: 'EUR',
result: '',
date: '',
};
handleSelect = (itemValue, itemIndex) => {
this.setState(
{
...this.state,
currencies: [itemValue],
result: null,
},
this.calculate,
);
};
handleInput = text => {
this.setState(
{
...this.state,
amount: text,
result: null,
date: null,
},
this.calculate,
);
};
calculate = () => {
const amount = this.state.amount;
if (amount === isNaN) {
return;
} else {
fetch(`https://api.exchangeratesapi.io/latest?base=${this.state.base}`)
.then(res => res.json())
.then(data => {
const date = data.date;
const result = (data.rates[this.state.convertTo] * amount).toFixed(4);
this.setState({
...this.state,
result,
date,
});
});
}
};
handleSwap = e => {
const base = this.state.base;
const convertTo = this.state.convertTo;
e.preventDefault();
this.setState(
{
...this.state,
convertTo: base,
base: convertTo,
result: null,
},
this.calculate,
);
};
render() {
const {currencies, base, amount, convertTo, result} = this.state;
return (
<View>
<Text>
{amount} {base} is equevalent to
</Text>
<Text>
{amount === '' ? '0' : result === null ? 'Calculating...' : result}{' '}
{convertTo}
</Text>
<View>
<View>
<View>
<TextInput
keyboardType="numeric"
value={amount}
onChangeText={this.handleInput}
/>
<Picker
selectedValue={base}
value={base}
onValueChange={this.handleSelect}>
{currencies.map((currency, index) => (
<Picker.Item label={currency} value={currency}>
{currency}
</Picker.Item>
))}
</Picker>
</View>
<View>
<TextInput
editable={false}
value={
amount === ''
? '0'
: result === null
? 'Calculating...'
: result
}
/>
<Picker
selectedValue={convertTo}
value={convertTo}
onValueChange={this.handleSelect}>
{currencies.map(currency => (
<Picker.Item label={currency} value={currency}>
{currency}
</Picker.Item>
))}
</Picker>
</View>
</View>
<View>
<Text onClick={this.handleSwap}>CLICK ME</Text>
</View>
</View>
</View>
);
}
}
export default CurrencyCashScreen;
Please help.
See below example
you need two separate functions
import React, {Component} from 'react';
import {View, Text, TextInput, Picker} from 'react-native';
class CurrencyCashScreen extends Component {
state = {
currencies: ['USD', 'AUD', 'SGD', 'PHP', 'EUR'],
base: 'PLN',
convertTo: 'EUR',
amount: '',
result: '',
date: '',
};
handleSelectPicker1 = itemValue => {
this.setState(
{
base:itemValue
},
);
};
handleSelectPicker2 = itemValue => {
this.setState(
{
convertTo:itemValue
},
);
};
render() {
const {currencies, base, amount, convertTo, result,pickerValue1,pickerValue2} = this.state;
console.log('this.state',pickerValue1,pickerValue2)
return (
<View style={{flex:1}}>
<Picker
selectedValue={base}
//value={base}
onValueChange={this.handleSelectPicker1}>
{currencies.map((currency, index) => (
<Picker.Item label={currency} value={currency}/>
))}
</Picker>
<Picker
selectedValue={convertTo}
//value={convertTo}
onValueChange={
this.handleSelectPicker2
}>
{currencies.map(currency => (
<Picker.Item label={currency} value={currency}/>
))}
</Picker>
</View>
);
}
}
export default CurrencyCashScreen;
hope this will help you. Change this according to your requirement. Feel free for doubts.
Technically .map() requires an array to be executed on the variable.
I guess itemValue is not an array what you pass to handleSelect. That's why you have that error. I think if you modify the code to handle currencies as an array then it should work.
handleSelect = itemValue => {
this.setState(
{
...this.state,
currencies: [itemValue],
result: null,
},
this.calculate,
);
};
I hope that helps!
More than likely currencies is not an array. Here is what I recommended:
Check to make sure that you've properly destructured your state earlier in the render function like const { currencies } = state; Any typos here may cause the error.
Make sure currencies is set with a sane default. If currencies is undefined when your component first mounts, you will get this error.
Use console.log, or a debugger to view the value of currencies. If it is not an array (including undefined) when you call the currencies.map method, then you will get this error.
Related
I'm making an app that have notes, and when develop the delete function, i faced this error, the useState do not update when use alongside with redux dispatch function ( even the redux function run, the useState do not run ) , i tried to create the same issue on codesandbox, but weird is it WORKING TOTALLY FINE ON WEB?!
Here is the code:
NoteList.tsx
function NoteList(props: noteListI) {
const { title, note, id, date, selectStatus } = props; //they are props
const nav = useNavigation(); //for navigation
const [isDeleteChecked, setDeleteChecked] = useState(false);
const dispatch = useDispatch();
const data = useSelector((state: RootState) => state.persistedReducer.note); // note item from redux
const toggleSelectedButton = useSelector(
(state: RootState) => state.toggle.enableSelectedButton
); // to show selected button icon
const onNavDetail = () => {
nav.navigate(RouteName.EDIT_NOTE, {
date: date,
note: note,
header: title,
id: id,
});
};
const toggleSelectButton = () => {
dispatch(switchToggle());
}; // toggle delete button function
const setDeleteItem = () => {
setDeleteChecked(!isDeleteChecked);
dispatch(toggleSelect({ id: id }));
}; ////==>>> the issue here the 'setDeleteChecked' not even work
return (
<TouchableOpacity
onLongPress={() => {
toggleSelectButton();
}}
style={CONTAINER}
onPress={() => (!toggleSelectedButton ? onNavDetail() : setDeleteItem())}
>
<View style={NOTE_ITEM_CONTAINER}>
<Text>{isDeleteChecked?.toString()}</Text> ==>always false, why????!
<View>
<View row centerV style={HEADER_CONTAINER}>
<View>
<AppText bold style={HEADER_TEXT}>
{title}
</AppText>
</View>
{toggleSelectedButton && (
<View>
{selectStatus ? ( ===> this is from redux and work but slow
<CheckIcon name="checkcircle" size={size.iconSize} />
) : (
<CheckIcon name="checkcircleo" size={size.iconSize} />
)}
</View>
)}
</View>
<View style={NOTE_CONTAINER}>
<AppText numberOfLines={7}>{note}</AppText>
</View>
</View>
<View
style={{
alignSelf: "flex-end",
flexDirection: "row",
alignItems: "center",
justifyContent: "space-between",
}}
>
<AppText>{moment(date).format("h:mmA MMM Do YY")}</AppText>
</View>
</View>
</TouchableOpacity>
);
}
export default memo(NoteList);
I use these from flatlist, here is the main flatlist code:
export default function NoteListScreen() {
const [user, setUser] = useState<any>();
const nav = useNavigation();
// useEffect(() => {
// dispatch(loadDefault());
// }, []);
const dispatch: AppDispatch = useDispatch();
const data = useSelector((state: RootState) => state.persistedReducer.note);
const userInfo: user = useSelector(
(state: RootState) => state.persistedReducer.firebase.userInfomation
);
useEffect(() => {
dispatch(fetchNote(userInfo.email)); //fetch note from firebase
}, []);
return (
<SafeAreaView style={CONTAINER}>
{data.length === 0 ? (
<>
<ScrollView>
<HeaderNote />
<AppText style={EMPTY_NOTE}>
Hmm, so don't have any secret yet
</AppText>
</ScrollView>
<FooterNote />
</>
) : (
<View style={CONTAINER}>
<FlatList
removeClippedSubviews
data={data}
style={{
marginBottom:
Platform.OS === "ios"
? onePercentHeight * 15
: onePercentHeight * 12,
}}
keyExtractor={() => {
return (
new Date().getTime().toString() +
Math.floor(
Math.random() * Math.floor(new Date().getTime())
).toString()
);
}}
ListHeaderComponent={() => <HeaderNote />}
renderItem={({ item, index }) => {
return (
<NoteList ==> here , the note list that faced error
note={item.note}
title={item.header}
date={item.date}
id={item.id}
selectStatus={item.selectStatus}
/>
);
}}
/>
<FooterNote />
</View>
)}
</SafeAreaView>
);
}
Here is the reducer code:
const noteReducer = createSlice({
name: "note",
initialState: NoteList,
reducers: {
addNote: (state, action: PayloadAction<NoteI>) => {
const newNote: NoteI = {
id:
new Date().getTime().toString() +
Math.floor(
Math.random() * Math.floor(new Date().getTime())
).toString(),
header: action.payload.header,
note: action.payload.note,
date: new Date(),
selectStatus: false,
};
state.push(newNote);
},
toggleSelect: (state, action: PayloadAction<NoteI>) => {
return state.map((item) => {
if (item.id === action.payload.id) {
return { ...item, selectStatus: !item.selectStatus };
}
return item;
});
}, ///========>This is the reducer using in the note function
loadDefault: (state) => {
return state.map((item) => {
return { ...item, selectStatus: false };
});
},
resetNote: (state) => {
return (state = []);
},
editNote: (state, action: PayloadAction<NoteI>) => {
return state.map((item) => {
if (item.id === action.payload.id) {
return {
...item,
note: action.payload.note,
header: action.payload.header,
date: action.payload.date,
};
}
return item;
});
},
},
extraReducers: (builder) => {
builder.addCase(fetchNote.fulfilled, (state, action) => {
state = [];
return state.concat(action.payload);
});
},
});
Here is the image of what i'm talking about, the code in image from noteList.tsx, the first piece of code i post here
Here is the quick gif:
In above gif, the false must return true then false everytime i click ( as above code ) but i don't why it never change value, the black dot also change color because it use value using in the same function using with this value, but when setDeleteItem fire, it NOT fire the setDeleteChecked(!isDeleteChecked)
Here is the demo that i made, but it WORK TOTALLY FINE, but in my app, it make weird error https://codesandbox.io/s/nostalgic-neumann-0497v?file=/redux/some-redux.tsx
Please help, i'm trying to provide must as i can, i stuck for days for this, thank you so much, if you need any detail, just tell me
I'm in react native app an I use typeScript too.
I have a functional component :
const Input: React.FunctionComponent<IInputProps> = ({
inputStyle,
placeHolderColor = EAppColors.DARK_GREY,
placeHolder,
value,
onChangeText,
autoFocus,
onFocus,
onBlur,
onSubmitEditing,
ref,
keyboardType = EKeyboardType.DEFAULT,
}) => {
return (
<StyledInput
testID="TextInputID"
placeholderTextColor={placeHolderColor}
placeholder={placeHolder}
...
I create some ref for different input before my render:
const firstNameRef = React.createRef<TextInput>();
const lastNameRef = React.createRef<TextInput>();
const birthDateRef = React.createRef<TextInput>();
and I use after this component in a class like that :
<StyledTextInput
label={I18n.t('auth.heading.firstNameLabel')}
errorText={errorText}
ref={firstNameRef}
autoFocus={true}
placeHolder={I18n.t('auth.placeHolder.firstName')}
isFocused={focusOnFirstFields}
hasError={hasError}
onFocus={() => this.setState({ focusOnFirstFields: true })}
onBlur={() => this.setState({ focusOnFirstFields: false })}
showClearButton={showFirstClearButton}
value={firstName}
onClearText={() => this.onClearText(1)}
onChangeText={(value: string) =>
this.setState({
firstName: value,
disabled: false,
showFirstClearButton: true,
})
}
onSubmitEditing={() => {
if (lastNameRef !== null && lastNameRef.current !== null) {
lastNameRef.current.focus();
}
}}
keyboardType={EKeyboardType.DEFAULT}
/>
But when I want to use onSubmitEditing for focus the next input, I have this error :
How can I resolve this issue ?
Thank You!
Like this:
const FancyButton = React.forwardRef</* type of ref*/HTMLButtonElement, /* component props */ComponentProps>((props, ref) => (
<button ref={ref} className="FancyButton">
{props.children}
</button>))
It will be correctly typed as
const FancyButton: React.ForwardRefExoticComponent<React.RefAttributes<HTMLButtonElement>>
(You don't need to use React.FunctionComponent when using forwardRef).
const Input = React.forwardRef<TextInput, IInputProps>(({
inputStyle,
placeHolderColor = EAppColors.DARK_GREY,
placeHolder,
value,
onChangeText,
autoFocus,
onFocus,
onBlur,
onSubmitEditing,
keyboardType = EKeyboardType.DEFAULT,
}, ref /* <--- ref is passed here!!*/) => {
// assuming this is a TextInput
return (
<StyledInput
ref={ref}
testID="TextInputID"
placeholderTextColor={placeHolderColor}
placeholder={placeHolder}
...
})
I faced a similar problem a few months ago. I solved it by doing:
import {TextInputProps, TextInput} from 'react-native';
type IProps = TextInputProps & {
labelText?: string;
};
const TextInputStd: React.FC<IProps> = React.forwardRef(
(
{
labelText,
...textInputProps
}: IProps,
ref: React.Ref<TextInput>,
) => {
const {styles} = useStyles(_styles);
return (
<>
<View style={[styles.textInputContainer, styles2.textInputContainer]}>
<Text style={styles.labelText}>{labelText || ''}</Text>
<View style={styles.inputWrapper}>
<TextInput style={styles.input} {...textInputProps} ref={ref} />
</View>
</View>
</>
);
},
);
Hope this gives you an idea.
not 100% sure what the question is here, but
<StyledInput
ref={ref}
testID="TextInputID"
placeholderTextColor={placeHolderColor}
placeholder={placeHolder}
...
should work, then you need to pass the ref in when calling this input.
how can I access a single element from an array nested in a state like this
state = {
modal: false,
post: [
{
key: "1",
title: "A Good Boi",
des: "He's a good boi and every one know it.",
image: require("../assets/dog.jpg"),
},
{
key: "2",
title: "John Cena",
des: "As you can see, You can't see me!",
image: require("../assets/cena.jpg"),
},
]
};
.....
<MyList.Provider
value={{
}}
>
<FlatList
data={this.state.post}
renderItem={({ item }) => (
<>
<TouchableOpacity
activeOpacity={0.7}
onPress={() => this.deleteItem(item)}
style={styles.Delete}
>
<MaterialCommunityIcons name="delete" color="red" size={30} />
</TouchableOpacity>
<TouchableOpacity
activeOpacity={0.7}
onPress={() => this.props.navigation.navigate("Edit", item)}
style={styles.Edit}
>
<MaterialCommunityIcons
name="playlist-edit"
color="green"
size={35}
/>
</TouchableOpacity>
<Card
title={item.title}
subTitle={item.des}
image={item.image}
onPress={() =>
this.props.navigation.navigate("Details", item)
}
/>
</>
)}
/>
</MyList.Provider>
how can I do this like this.state.post({title}) or some way else??
I need to use this values with context so I can share and change some particular data with between 2 screens. I know to pass data I need to use context or navigation.navigate("route name",item). But if I use navigation I won't able to edit it but how can I pass data in context value from array set, if I do this.state.post it will return whole list and if i do this.state.post[0].title it will return only title of that post. So how can i do this? Please help
You have to indicate the index of the object you’re trying to access in the array. For instance to access the first object in the array you can do this
this.state.post[0]
below is my solution which follows the logic i think you are trying to achieve. I have used a flatlist
Let me know if it helps
import React, { Component } from 'react';
import {
View,
Text,
StyleSheet,
TouchableOpacity,
FlatList,
} from 'react-native';
export default class MyComponent extends Component {
constructor(props) {
super(props);
this.state = {
modal: false,
post: [
{
key: "1",
title: "A Good Boi",
des: "He's a good boi and every one know it.",
image: require("../assets/dog.jpg"),
},
{
key: "2",
title: "John Cena",
des: "As you can see, You can't see me!",
image: require("../assets/cena.jpg"),
},
]
};
}
handleEdit(item) {
const { post } = this.state;
const extractIndex = post.findIndex(e => e.key === item.key);
const newPost = post[extractIndex];
this.props.navigation.navigate('Edit', { newPost })
this.setState({ post });
}
handleDelete(item) {
const { post } = this.state;
const newPost = post.filter(e => e.key !== item.key);
this.setState({ post: newPost });
}
renderItem = ({ item }) => {
return (
<View>
<Text>
{item.title}
</Text>
<TouchableOpacity key={item.key} onPress={this.handleEdit.bind(this, item)}>
<Text>Edit</Text>
</TouchableOpacity>
<TouchableOpacity key={item.key} onPress={this.handleDelete.bind(this, item)}>
<Text>Delete</Text>
</TouchableOpacity>
</View>
);
}
render() {
return (
<View style={styles.container}>
<FlatList
data={this.state.post}
renderItem={this.renderItem}
keyExtractor={(item, index) => index.toString()}
extraData={this.state}
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
},
});
Use .map() function
Ex-
var cat_data = categories_list.map(function (item) {
var cat_data = categories_list.map(function (item) {
return {
name: item.Name,
thumb_url: item.PictureModel.ImageUrl,
cat_id: item.Id.toString(),
};
});
this.setState({
data: cat_data,
});
Here in this screen I am maping array ("above array) value with checkbox ,there are some amout "data.TransactionAmount" I have to calculate the sum of all and send to next screen,
but if I uncheck any of the list amount should minus .Like there are 3 values - 1050+1050+1050 =3150 and if I unchecked single value then it should be 1050+1050-1050=2100 and it should updae in below button.
If i am uncheking single list all list is getting unchecked .
in state "sum" im getting total sum be default and value is coming in button . but if I do uncheck any of the list ,value should minus .
Please help , Thanks ,
Below link is refrence what i am implementing .
https://xd.adobe.com/view/d733da48-5d0c-47ca-7ded-6fc8f0f609cf-a102/screen/37cb15c6-b56a-4b98-8612-e9b86d0dd34c/Android-Mobile-147/?fullscreen
// Below is the array value
financialTransactionDetail: Array(3)
0:
AdjustedAmount: "0"
NetTransactionAmount: "1050"
TransactionAmount: 1050
1:
AdjustedAmount: "0"
NetTransactionAmount: "1050"
TransactionAmount: 1050
2:
AdjustedAmount: "0"
NetTransactionAmount: "1050"
Status: "Unpaid"
TransactionAmount: 1050
this.state = {
title: 'Payments against invoice',
icon: 'sim',
mobile:navigation.state.params.customer.service.serviceNumber,
isChecked:true,
sum :financialTransactionDetail.financialTransactionDetail.reduce((a, c) => { return a + c.TransactionAmount}, 0),
transactionAmount :''
}
handleChange(key , value){
this.setState({
isChecked:!this.state.isChecked})
}
handleChangeSum = (sum) => {
this.setState({
sum: sum
});
}
{ !_.isEmpty(financialTransactionDetail.financialTransactionDetail) && financialTransactionDetail.financialTransactionDetail.map(
(data, index) => {
return(
<View key={index} style={{flexDirection:'row', padding:10, alignItems:'center', justifyContent:'space-between'}}>
<View style={{paddingRight:10, marginRight:10}}>
<CheckBox style={styles.checkBox} color="#00678f" checked={this.state.isChecked} onPress={() =>this.handleChange()}/>
</View>
<View style={{flexDirection:'column',flex:1, padding:10, borderWidth:1, borderColor:'lightgrey', borderRadius:10}}>
<View style={{flexDirection:'row', alignItems:'center'}}>
{!this.state.isChecked && <RegularText text={`₦ ${data.TransactionAmount}`} style={{paddingBottom:10, paddingRight:5}}/>}
<SmallText text="From 1-Jan-2019 to 31-Jan-2019" style={{paddingBottom:10}}/>
</View>
{this.state.isChecked &&
<RegularText text={`₦ ${data.TransactionAmount}`} style={{borderColor: '#00fff', borderBottomWidth:1}}>
</RegularText>
}
</View>
</View>
)
}
)
}
<View>
<Button full onPress={()=>navigation.navigate('PaymentOptionsContainer',sum)}>
<Text>Receive Payment ({sum})</Text>
</Button>
</View>
Thanks
Instead of is isChecked use checked which is array like below in state
// Instead
isChecked: true
// Use below one
checked: financialTransactionDetail.map(() => true)
Now let the checkbox point based on index like below
// Instead
<CheckBox style={styles.checkBox} color="#00678f" checked={this.state.isChecked} onPress={() =>this.handleChange()}/>
// Use Below one
<CheckBox style={styles.checkBox} color="#00678f" checked={this.state.checked[index]} onPress={() =>this.handleChange(index)}/>
Now change handle onchange of checkbox
handleChange(index){
let newChecked = [...checked];
newChecked[index] = !newChecked[index];
this.setState({checked: newChecked})
}
Finally based on checked array calculate sum
let sum = 0;
this.state.checked.map((value, index) => {
if(value) {
sum += financialTransactionDetail[i].TransactionAmount;
}
});
Your code seems to be very involved with libraries and proprietary code.
I'm sure you're just looking for some methods that can help update the total balance upon checking/unchecking an amount.
Here's a working sandbox I've made for you that you can replicate: https://codesandbox.io/s/zen-swanson-2ccxo
Working code:
import React from "react";
import ReactDOM from "react-dom";
import "./styles.css";
const data = [{ amount: 1050 }, { amount: 1025 }, { amount: 1000 }];
class App extends React.Component {
state = {
data: [],
total: null
};
componentDidMount() {
const dataWithCheckedProp = data.map(item => {
return { ...item, checked: true };
});
let total = data.reduce((total, item) => total + item.amount, 0);
this.setState({
data: dataWithCheckedProp,
total: total
});
}
handleOnChange = index => {
const dataCopy = [...this.state.data];
dataCopy[index].checked = !dataCopy[index].checked;
let balance = dataCopy.reduce((total, item) => {
if (item.checked) {
total = total + item.amount;
}
return total;
}, 0);
this.setState({
data: dataCopy,
total: balance
});
};
render() {
const { data, total } = this.state;
return (
<div>
{data.map((item, index) => {
return (
<div>
<input
type="checkbox"
checked={item.checked}
onChange={() => this.handleOnChange(index)}
/>
<label>{item.amount}</label>
</div>
);
})}
<h4>Total: {total}</h4>
</div>
);
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
In summary, here are the steps you need to take:
You really just need to give each object in the
financialTransactionDetail array a checked property. See logic
in componentDidMount() where we clone the financial data array and give each object a new prop.
In your change-handler function, have it accept an index, which
refers to the item that was toggled. The index will be passed via
the 2nd parameter of .map(). See handleOnChange()logic
Within handleOnChange(), use the index to find the object within
the data-set and simply toggle its checked boolean value. Then
with the updated array, have your .reduce() function add only
those items that are checked.
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;