In my Applikation I render a Expo FlatList to show created Events.
If the user has created or joined this event, he should be able to see the images. If not, they should be hidden.
I would now store the creator
and the guests
in the database and would have to compare this with the currentUser from the Firebase Auth beforehand.
However, I face the problem that I can’t tell the FlatList
which items should be rendered and which shouldn’t.
Does anyone knows a solution for conditional render a FlatList?
Fullcode
JavaScript
x
84
84
1
import React, { Component } from 'react';
2
import { FlatList, Box, } from "native-base";
3
import { StyleSheet } from 'react-native'
4
import EventCard from "./EventCard.js";
5
import { collection, getDocs } from 'firebase/firestore';
6
import { firestore, auth } from '../firebase.js'
7
import { getStorage } from "firebase/storage"
8
9
export default class Events extends Component {
10
11
constructor(props) {
12
super(props);
13
this.currentUser = auth.currentUser
14
this.navigation = this.props.navigation
15
this.storage = getStorage()
16
this.querySnapshot = getDocs(collection(firestore, 'events'));
17
this.state = {
18
isLoading: true,
19
fetch: false,
20
eventData: {
21
adress: '',
22
hosts: '',
23
description: '',
24
eventtitle: '',
25
invitecode: '',
26
key: '',
27
timestamp: '',
28
owner: '',
29
}
30
}
31
}
32
33
componentDidMount() {
34
this.loadEventsFromFirebase()
35
36
}
37
38
// reload on pull down
39
onRefresh() {
40
this.setState({
41
fetch: true
42
});
43
this.loadEventsFromFirebase()
44
}
45
46
loadEventsFromFirebase() {
47
let data = []
48
this.querySnapshot.then(querySnapshot => {
49
querySnapshot.docs.map(doc => {
50
data.push(doc.data())
51
})
52
this.setState({
53
eventData: data,
54
fetch: false,
55
});
56
});
57
58
}
59
60
render() {
61
62
return (
63
<Box style={styles.container} _dark={{ bg: "blueGray.900" }} _light={{ bg: "blueGray.50" }}>
64
<FlatList
65
showsVerticalScrollIndicator={false}
66
onRefresh={() => this.onRefresh()}
67
refreshing={this.state.fetch}
68
data={this.state.eventData}
69
keyExtractor={item => item.key}
70
renderItem={({ item }) => (<EventCard key={Date.now()} eventData={item} />
71
)}
72
/>
73
</Box>
74
)
75
}
76
}
77
78
const styles = StyleSheet.create({
79
container: {
80
alignSelf: 'stretch',
81
alignItems: 'center'
82
},
83
})
84
Advertisement
Answer
You can filter the events data before setting it to the state
I am assuming, events have a owner
property which is the userId, it has an array of userIds in guests
property
JavaScript
1
15
15
1
loadEventsFromFirebase() {
2
let data = []
3
this.querySnapshot.then(querySnapshot => {
4
querySnapshot.docs.map(doc => {
5
data.push(doc.data())
6
})
7
const allowedData = data.filter(d=> (d.owner == this.currentUser) || d.guests.includes(this.currentUser));
8
this.setState({
9
eventData: allowedData,
10
fetch: false,
11
});
12
});
13
14
}
15