How to pass Flatlist items to another screens Flatlist? - javascript

How do I pass FlatList items to another screen that also have a FlatList?
I'm using React Navigation V5 to pass the FlatList item to the other screen. Thats working fine. I can see the text when only using ´<Text.>{details.id}</Text .>´ but not when trying to pass it to FlatList, then there is nothing.
CODE
import React, { useState } from 'react';
import {
View,
TextInput,
FlatList,
Text,
TouchableOpacity,
Linking,
Modal,
ScrollView,
} from 'react-native';
import { useTheme } from '../Data/ThemeContext';
import DataBase from '../Data/DataBase';
import Octicons from 'react-native-vector-icons/Octicons';
export default function Home({ navigation }) {
const [search, setSearch] = useState('');
const [masterDataSource, setMasterDataSource] = useState(DataBase);
const [modalVisible, setModalVisible] = useState(false);
const [details, setDetails] = useState('');
const { colors } = useTheme();
const filteredDataSource = masterDataSource.filter((item) => {
return (
item.name.includes(search) ||
(item.id && item.id.includes(search)) ||
(item.gluten && item.gluten.includes(search)) ||
(item.company && item.company.includes(search))
);
});
const itemSeparatorComponent = () => {
return (
<View
style={{
margin: 3,
}}></View>
);
};
const emptyComponent = () => {
return (
<View style={{ alignItems: 'center' }}>
<Text style={{ color: colors.text }}>Finns inte produkten med?</Text>
<View style={{ marginTop: 30 }}>
<TouchableOpacity
onPress={() => Linking.openURL('')}>
<Text
style={{
color: colors.text,
borderWidth: 1,
borderColor: colors.text,
padding: 10,
borderRadius: 5,
backgroundColor: colors.card,
}}>
KONTAKTA OSS
</Text>
</TouchableOpacity>
</View>
</View>
);
};
const renderItem = ({ item }) => {
return (
<View>
<TouchableOpacity
style={{
marginLeft: 20,
marginRight: 20,
elevation: 3,
backgroundColor: colors.card,
borderRadius: 10,
}}
onPress={() => {
setModalVisible(true);
setDetails(item);
}}>
<View style={{ margin: 10 }}>
<Text style={{ color: colors.text }}>{item.company}</Text>
<Text style={{ color: colors.text, fontWeight: '700' }}>
{item.name}
</Text>
<Text style={{ color: colors.text }}>{item.gluten}</Text>
<Text style={{ color: colors.text }}>{item.id}</Text>
</View>
</TouchableOpacity>
</View>
);
};
return (
<View style={{ flex: 1, backgroundColor: colors.background }}>
<Modal
animationType="none"
hardwareAccelerated={true}
transparent={true}
visible={modalVisible}
onRequestClose={() => {
setModalVisible(!modalVisible);
}}>
<View
style={{
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: 'rgba(0,0,0,0.8)',
}}>
<View
style={{
backgroundColor: colors.Modal,
padding: 35,
borderRadius: 10,
width: '80%',
height: '80%',
}}>
<ScrollView showsVerticalScrollIndicator={false}>
<View style={{ marginTop: 20 }}>
<Text style={{ color: colors.text }}>{details.company}</Text>
<Text
style={{ color: colors.text, marginTop: 20, fontSize: 20 }}>
{details.name}
</Text>
<Text style={{ color: colors.text, marginTop: 20 }}>
{details.gluten}
</Text>
<Text style={{ color: colors.text, marginTop: 20 }}>
Ingredienser
</Text>
<Text style={{ color: colors.text, marginTop: 2 }}>
{details.ingredients}
</Text>
<Text style={{ color: colors.text, marginTop: 30 }}>
{details.id}
</Text>
</View>
</ScrollView>
<View
style={{
borderTopWidth: 1,
borderTopColor: colors.text,
marginBottom: 10,
}}></View>
<View
style={{ flexDirection: 'row', justifyContent: 'space-evenly' }}>
<TouchableOpacity
onPress={() => {
const updated = [...masterDataSource];
updated.find(
(item) => item.id === details.id,
).selected = true;
setMasterDataSource(updated);
navigation.navigate('Inköpslista', {
items: updated.filter((item) => item.selected),
});
}}>
<Text>Lägg i Inköpslistan</Text>
</TouchableOpacity>
<TouchableOpacity
onPress={() => {
setModalVisible(false);
}}>
<Text style={{ alignSelf: 'center', color: '#FF0000' }}>
Stäng
</Text>
</TouchableOpacity>
</View>
</View>
</View>
</Modal>
<View
style={{
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'center',
padding: 20,
backgroundColor: colors.Textinput,
elevation: 12,
}}>
<TextInput
style={{
flex: 1,
backgroundColor: '#fff',
borderTopLeftRadius: 5,
borderBottomLeftRadius: 5,
}}
placeholder=" SÖK PRODUKT NAMN / STRECKKOD"
placeholderTextColor="#000"
onChangeText={(text) => setSearch(text)}
value={search}
autoCapitalize="words"
/>
<Octicons
style={{
marginLeft: 1,
padding: 13,
backgroundColor: '#fff',
height: 49,
borderTopRightRadius: 5,
borderBottomRightRadius: 5,
}}
name="checklist"
size={25}
color="#000"
onPress={() =>
navigation.navigate('Inköpslista', {
items: masterDataSource.filter((item) => item.selected),
})
}
/>
</View>
<View style={{ flex: 1, marginTop: 20 }}>
<FlatList
data={filteredDataSource}
ItemSeparatorComponent={itemSeparatorComponent}
keyExtractor={(_, index) => index.toString()}
renderItem={renderItem}
initialNumToRender={4}
maxToRenderPerBatch={5}
windowSize={10}
removeClippedSubviews={true}
updateCellsBatchingPeriod={100}
showsVerticalScrollIndicator={true}
ListEmptyComponent={emptyComponent}
contentContainerStyle={{ paddingBottom: 20 }}
/>
</View>
</View>
);
}
SECOND SCREEN
import React from 'react';
import { View, Text, FlatList, Button } from 'react-native';
export default function ShoppingList({ route, navigation }) {
const RenderItem = ({ item }) => {
return (
<TouchableOpacity
style={{ marginHorizontal: 10, marginVertical: 15 }}
onPress={() => {}}>
<Text>{item.id}</Text>
<Text>{item.name}</Text>
</TouchableOpacity>
);
};
return (
<View
style={{
flex: 1,
alignItems: 'center',
justifyContent: 'center',
marginTop: 30,
}}>
<Button title="Go back" onPress={() => navigation.goBack()} />
<FlatList
data={route.params && route.params.items}
renderItem={RenderItem}
/>
</View>
);
}

Based on your question, this is the flow that you want
User has flat list with a set of items
When an item is clicked a modal is opened
If the user wants he clicks 'Add to cart' which will add item to cart and open cart.
When cart is opened user is shown a flatlist with the selected items.
Screen 1 : Home
Here you already have a modal but you pass a single item instead of an array.
So the better way is to use the masterDataSource state that you have and add a 'selected' property to it.
So the button in the Modal would be like this
<Button
title="Add and View Cart"
onPress={() => {
const updated = [...masterDataSource];
updated.find((item) => item.id === details.id).selected = true;
setMasterDataSource(updated);
navigation.navigate('Cart', {
items: updated.filter((item) => item.selected),
});
}}
/>
Once you click the Button you would be taken to the cart page with the items array which you have selected (This will have the previous items as well).
The Cart screen will have a Flatlist to show the items that are passed via params like below. RenderItem can be the code for your item.
<FlatList
data={route.params && route.params.items}
renderItem={RenderItem}
/>
You can run the sample below
https://snack.expo.io/#guruparan/cartexample
(Modal doesnt work properly on web you can try the android version)

According to React Native Docs, the prop data on FlatList should contain an Array, like this [{...}] or this [{...},{...},{...}...]. But you are trying to pass an Object to the FlatList on the ShoppingList screen, like this {...}.
On ShoppingList Screen when you're destructuring like the following
const { details } = route.params;
You are creating an object, which looks like this {...}
So you need to convert it to an array. Use the following code snippet
const itemInfo = []
itemInfo.push(details)
Now just pass itemInfo to data prop of FlatList.
Your ShoppingList screen should look like this.
import React from 'react';
import {
View,
FlatList,
Text,
} from 'react-native';
export default function ShoppingList({ route }) {
const { details } = route.params;
const itemInfo = [];
itemInfo.push(details);
return (
<View style={{ flex: 1, backgroundColor: "white" }}>
<FlatList
data={itemInfo}
keyExtractor={(item) => item.id.toString()}
renderItem={({ item }) => (
<View>
<Text style={{ color: "black" }}>{item.company}</Text>
<Text style={{ color: "black" }}>{item.name}</Text>
<Text style={{ color: "black" }}>{item.gluten}</Text>
<Text style={{ color: "black" }}>{item.id}</Text>
</View>
)}
/>
</View>
);
}

Related

How to like individual image specific to each user. Through expo/react native/firebase

My main issue with my current react native app is that when a user searches for a nft using a web3 api im using, i render a like button next to every image of the nft. I added some logic for making the like button red but when i like a NFT all the other like buttons for all the other NFT's get liked. How can i fix this to where only the specific like button that gets pressed shows that it is pressed.
code:
export const Profile = ({setLoggedIn}) => {
const [profileData, setProfileData] = useState([]);
const [apiQ,setApiQ] = useState("")
const [nfttei,setNftTei] = useState("")
const [comments,setComments] = useState([])
const[commentText,setCommentText] = useState("")
async function getData () {
const options = {method: 'GET', headers: {accept: 'application/json', 'X-API-Key': 'WYON0dXwg4zG3GSsaPb79ofaPTLAbDUpmt01OuTlZihmzoH1F059it3bdsXSou0t'}};
const data = await fetch(`https://deep-index.moralis.io/api/v2/nft/search?chain=eth&format=decimal&q=${apiQ}&filter=name&limit=10`, options)
const ddata = await data.json()
setProfileData(ddata.result)
}
async function handleNftIn () {
setApiQ(nfttei)
setNftTei("")
}
useEffect(() => {
getData();
}, [apiQ]);
function liked (id) {
setPressed(true)
}
const [pressed,setPressed] = useState(false)
return (
<View style={{padding: 20}}>
<Text style={{fontSize: 40, fontWeight: "700"}}>NFTS</Text>
<View style={{marginBottom: 20}}>
<Text style={{fontSize: 25, fontWeight: "650", marginBottom: 10}}>What kind of NFT?</Text>
<View style={{flexDirection: "row", justifyContent: "space-between", alignItems: "center"}}>
<TextInput
placeholder='type nft keyword'
style={{
backgroundColor: "#D1D1D1",
borderRadius: 20,
padding: 10,
fontSize: 16,
width: "60%"
}}
onChangeText={(val) => setNftTei(val)}
value={nfttei}
/>
<AntDesign name="rightcircle" size={30} color="#3A84EC" onPress={handleNftIn}/>
</View>
</View>
<ScrollView>
{profileData ? <>
{profileData.map((el, key,id) =>
<View style={{
backgroundColor: "#fff",
padding: 10,
borderRadius: 20,
marginBottom: 20
}} key={key}>
<View style={{position: "relative"}}>
<View style={{position: "absolute", zIndex: 10, right: 0, backgroundColor: "#fff", padding: 8,borderRadius: 30, marginRight: 20, marginTop: 10}}>
<AntDesign onPress={(id) => liked(id)} name="heart" size={24} color={pressed ? "#FF717B": "grey"} />
</View>
{JSON.parse(el.metadata).image.includes("https") ? <>
<Image source={{
uri: `${JSON.parse(el.metadata).image}`
}} style={{width: "1005", height: 200, borderRadius: 30, width: "100%"}}/>
</>: null}
</View>
<View style={{marginTop: 20}}>
<View style={{flexDirection: "row", alignItems:"center"}}>
<Text style={{marginRight:10, color: "grey"}}>ID</Text>
<View style={{width: 10,height:10,backgroundColor:"#000", borderRadius:50}}></View>
<Text style={{marginLeft: 10}}>{el.token_id}</Text>
</View>
<Text style={{fontSize: 20, fontWeight: "700", marginBottom: 10}} key={key}>{JSON.parse(el.metadata).name}</Text>
<Text>{JSON.parse(el.metadata).description}</Text>
<View style={{backgroundColor: "#000", borderRadius: 10,padding:7,justifyContent: "center", alignItems: "center"}}>
{el.token_uri.includes("https") ? <>
<A style={{color:"white", fontSize: 19}} href={el.token_uri}><Text>learn More</Text></A>
</> : <Text>Learn More</Text>}
</View>
</View>
</View>
)}
</>: <>
<Text style={{
fontWeight:"700",
color:"#000",
fontSize:20,
marginBottom:20
}}>Try searching something! Anything!</Text>
<Image source={{
uri:"https://mir-s3-cdn-cf.behance.net/project_modules/max_1200/50e513115094373.6047d1f4cf3f1.jpg"
}} style={{
width:"100%",
borderRadius:20,
height:500
}}/>
</>}
</ScrollView>
</View>
)
}
image:
what its giving me:

React Native - How to set blurRadius onto a selected image

My app displays images and other info getting data from a JSON, and I want to set a blurRadius on the selected image when the unblur function is called.
My code is the following:
const [blur, setBlur] = useState(160);
const unblur = () => {
if(blur == 160){
setBlur(0);
}
}
{isLoading ? <ActivityIndicator/> : (
<FlatList
data={data}
keyExtractor={({ id }, index) => id}
renderItem={({ item }) => (
<>
<Text style={{ textAlign: "left", color: 'white', fontSize: 24 }}>
<Image style={{ alignSelf: "center" }} source={{uri: item.profile_picture, width: 48, height: 48}} />
{item.username}
</Text>
<TouchableOpacity onPress={() => unblur()}>
<Image style={{ alignSelf: "center" }} blurRadius={blur} source={{uri: item.picture, width: 400, height: 320}} />
</TouchableOpacity>
<Text style={{ textAlign: "left", color: 'white', fontSize: 24 }}>
ID {item.id}
</Text>
<Text>
{'\n'}{'\n'}
</Text>
</>
)}
/>
)}
I want to change the {blur} value for a given image when I tap the TouchableOpacity component of the image I want to unblur. Right in this moment when I tap an image, all the images in the list are getting unblurred.
You should add the blur values inside your items like this. Create a new components called Items. Then, add the blur state inside it. (not inside Main).
const Main = () => {
if (isLoading) {
return;
<ActivityIndicator />;
}
return (
<FlatList
data={data}
keyExtractor={({ id }, index) => id}
renderItem={({ item }) => <Item item={item} />}
/>
);
};
const Item = ({ item }) => {
const [blur, setBlur] = useState(160);
const unblur = () => {
if (blur == 160) {
setBlur(0);
}
};
return (
<>
<Text style={{ textAlign: "left", color: "white", fontSize: 24 }}>
<Image
style={{ alignSelf: "center" }}
source={{ uri: item.profile_picture, width: 48, height: 48 }}
/>
{item.username}
</Text>
<TouchableOpacity onPress={() => unblur()}>
<Image
style={{ alignSelf: "center" }}
blurRadius={blur}
source={{ uri: item.picture, width: 400, height: 320 }}
/>
</TouchableOpacity>
<Text style={{ textAlign: "left", color: "white", fontSize: 24 }}>
ID {item.id}
</Text>
<Text>
{"\n"}
{"\n"}
</Text>
</>
);
};
Also, may I suggest you can use 'onPressIn'. That way, image will unblur when the finger tap the image, not press the image. But that was your decision.

React-Native FlatList is not scrolling

I am quite new to react native. I have created a FlatList for rendering this list of items, however, it is not scrolling. I've googled it for hours and tried nearly everything suggested in stack overflow threads - removed flex, added flex, wrapped it in a view, but nothing seems to work.
Here is my code (the issue is in the second FlatList) -
return(
<View style = {{ height: '100%' }}>
<View style = {{ width: '100%' }}>
<AppHeader />
</View>
<View style = {{ width: '100%'}}>
<View style = {{ width: '70%', alignSelf: 'center', flex: 1 }}>
<View>
<FlatList
data = {this.getTodayDay()}
renderItem = {this.renderItemDays}
keyExtractor = {this.keyExtractor}
/>
</View>
<FlatList
data = {this.getVisibleHours()}
renderItem = {this.renderItem}
keyExtractor = {this.keyExtractor}
scrollEnabled = {true}
/>
</View>
</View>
</View>
this.renderItem -
renderItem = () => {
// irrelevant code
if( isClass === true ){
return(
<ListItem bottomDivider = {true} style = {styles.renderItemActiveClass}>
<ListItem.Content>
<TouchableOpacity
onPress = {()=>{
this.props.navigation.navigate('ClassDetailsScreen', { "data": classData })
}}>
<ListItem.Title>{ definiteClassTime }</ListItem.Title>
<ListItem.Subtitle>{ classData.class_name }</ListItem.Subtitle>
</TouchableOpacity>
</ListItem.Content>
</ListItem>
)
}
else{
return(
<ListItem bottomDivider = {true} style = {styles.renderItemClass}
containerStyle = {styles.renderItemContent}>
<ListItem.Content>
<ListItem.Title>{item}:00</ListItem.Title>
<ListItem.Subtitle>No Class</ListItem.Subtitle>
</ListItem.Content>
</ListItem>
)
}
}
the StyleSheet -
renderItemClass: {
borderColor: 'purple',
borderWidth: 2
},
renderItemActiveClass: {
borderColor: 'green',
borderWidth: 2
},
renderItemContent: {
},
Could somebody please tell me what I'm doing wrong?
Add a height to both the flatlist. And also wrap your second flatlist within a seperate view. Here is an example:
return (
<View style={{ height: "100%" }}>
<View style={{ width: "100%" }}>
<AppHeader />
</View>
<View style={{ width: "100%" }}>
<View style={{ width: "70%", alignSelf: "center", flex: 1 }}>
<View style={{ height: 60, alignSelf: "center" }}>
<FlatList
data={this.getTodayDay()}
renderItem={this.renderItemDays}
keyExtractor={this.keyExtractor}
/>
</View>
<View style={{ height: 60, alignSelf: "center" }}>
<FlatList
data={this.getVisibleHours()}
renderItem={this.renderItem}
keyExtractor={this.keyExtractor}
scrollEnabled={true}
/>
</View>
</View>
</View>
</View>
);

Not able display data in flat list after fetched data from firestore

I have some data in my firestore. The structure is :
User -> DocId(Some id)-> name(String), number(String), friends (array)
I got the friends array and i append to my local array data. Now when i render in the flat list. Its not showing. But same temp data which i created locally its working fine. I check my array data count after i fetch from firestore. Its showing correct count. But not able to display the data in flat list.
My code :
import firebase from '#react-native-firebase/app';
import firestore from '#react-native-firebase/firestore';
UserArray =[]
export default class HomeScreen extends React.Component {
constructor(props) {
super(props);
this.state = {
UserArray: [],
}
}
componentWillMount() {
firebase.firestore().doc(`User/${'beQVEcfLsXV8JhA8L2SDDq03bmD3'}`)
.get()
.then(doc => {
this.setState({UserArray: doc.data().friends})
})
}
renderPost = post => {
return (
<View style={styles.feedItem}>
<Feather name="book" style={styles.avatar} size={30}/>
<View style={{ flex: 1 }}>
<View style={{ flexDirection: "row", justifyContent: "space-between", alignItems: "center" }}>
<View>
<Text style={styles.name}>{post.name}</Text>
<Text style={styles.timestamp}>{post.name} | {post.name}</Text>
</View>
</View>
</View>
<Feather name="chevron-right" style={{color: "#808080", alignSelf: 'center'}} size={20}/>
</View>
);
};
render() {
return (
<View style={styles.container}>
{
UserArray.length ?
(<FlatList
style={styles.feed}
data={UserArray}
keyExtractor={(index) => index.toString()}
renderItem={({ item }) => this.renderPost(item)}
// keyExtractor={item => item.id}
showsVerticalScrollIndicator={false}
></FlatList>) :
(
<View style={{ width: '70%', alignSelf: 'center',justifyContent: 'center' , alignItems: 'center', marginTop: '20%'}}>
<Feather name="smile" color="#009387" size={40}/>
<Text style={{paddingTop: 20, textAlign: 'center', fontSize: 15, fontWeight: 'bold', color: '#A9A9A9'}}>Hey folk, You dont' have any friends list</Text>
</View>
)
}
</View>
);
}
}
In my screen i am always getting. You don't have any data.
But in componentDidMount() after i fetch data from firestore. Inside my then :
.then(doc => {
alert(UserArray.length);
})
Its showing correct array count. Here is my friends array :
{
"name": "quaroe",
"number": "3940904",
friends: [
{
"name": "alber"
},
{
"name": "romea"
},
{
"name": "basea"
}
]
}
my doubt is that render is called before componentDidMount. But i tried componentWillMount. And i added alert. Always render called first and then only componentWillMount or componentDidMount is getting called
Put your UseArray in the state instead. I believe the flatlist is not showing anything because when it is rendered your firebase function is not yet completed so UseArray is empty. And render cant detect changes of your constant UseArray that why it's not showing any list even if your fetch is succesful.
try this
import firestore from '#react-native-firebase/firestore';
export default class HomeScreen extends React.Component {
constructor(props) {
super(props);
this.state = {
userArray: [],
};
}
componentDidMount() {
firebase
.firestore()
.doc(`User/${'beQVEcfLsXV8JhA8L2SDDq03bmD3'}`)
.get()
.then(doc => {
this.setState({userArray: doc.data().friends});
});
}
renderPost = post => {
return (
<View style={styles.feedItem}>
<Feather name="book" style={styles.avatar} size={30} />
<View style={{flex: 1}}>
<View
style={{
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center',
}}>
<View>
<Text style={styles.name}>{post.name}</Text>
<Text style={styles.timestamp}>
{post.name} | {post.name}
</Text>
</View>
</View>
</View>
<Feather
name="chevron-right"
style={{color: '#808080', alignSelf: 'center'}}
size={20}
/>
</View>
);
};
render() {
return (
<View style={styles.container}>
{this.state.userArray && this.state.userArray.length > 0 ? (
<FlatList
style={styles.feed}
data={this.state.userArray}
keyExtractor={index => index.toString()}
renderItem={({item}) => this.renderPost(item)}
// keyExtractor={item => item.id}
showsVerticalScrollIndicator={false}
/>
) : (
<View
style={{
width: '70%',
alignSelf: 'center',
justifyContent: 'center',
alignItems: 'center',
marginTop: '20%',
}}>
<Feather name="smile" color="#009387" size={40} />
<Text
style={{
paddingTop: 20,
textAlign: 'center',
fontSize: 15,
fontWeight: 'bold',
color: '#A9A9A9',
}}>
Hey folk, You dont' have any friends list
</Text>
</View>
)}
</View>
);
}
}

Can't Re-render FlatList after deleting last item Although use extraData - React Native

I'm tried to re-render Flat list but can't be updated anymore,
I'm getting the data from real-time DB and passed to Flatlist as a data props,
and write a function to delete an item from the list and DB and work very well, but when I delete the last one of the list I can not see Empty screen "List" just stock with the last one I've deleted Although it's deleted in DB!
code
import React, { Component } from 'react';
import { View, Text, StyleSheet, FlatList, ScrollView, TouchableOpacity } from 'react-native';
import firebase from "react-native-firebase";
import Icon from 'react-native-vector-icons/Ionicons';
class UserFavorites extends Component {
constructor(props) {
super(props);
this.state = {
currentUser: null,
favorites: [],
}
}
componentDidMount() {
const currentUser = firebase.auth().currentUser.uid;
this.setState({ currentUser });
const favorites = firebase.database().ref(`favorites/${currentUser}`);
favorites.on("value", (snapshot) => {
let favorites = []
snapshot.forEach((childSnapshot) => {
favorites.push({
ProviderId: childSnapshot.val().ProviderId,
providerName: childSnapshot.val().providerName,
providerService: childSnapshot.val().providerService,
});
this.setState({ favorites })
});
});
}
_listEmptyComponent = () => {
return (
<View style={styles.container}>
<Text style={{ alignSelf: "center" }}> No favorites Provider Found :O</Text>
</View>
)
}
render() {
const { fav } = this.state;
return (
<View style={styles.container} >
<FlatList data={this.state.favorites}
key={Math.random() * 1000}
contentContainerStyle={{ flexGrow: 1 }}
ListEmptyComponent={this._listEmptyComponent()}
extraData={this.state}
renderItem={({ item }) => {
return (
<ScrollView>
<TouchableOpacity>
<View
style={{
flex: 1,
paddingLeft: 15,
paddingRight: 10,
height: 105,
alignItems: "center",
backgroundColor: "#fafafa",
flexDirection: "row",
borderBottomWidth: .8,
borderBottomColor: "#aaa"
}}>
<Icon style={{ alignSelf: "center" }} name="ios-contact" size={60} color="#1567d3" />
<View style={{ flex: 1, padding: 5, flexDirection: "row" }}>
<View style={{ marginLeft: 27 }}>
<Text style={{
fontSize: 18,
fontWeight: "800",
fontFamily: 'Gill Sans',
color: '#000',
}}>
{item.providerName}
</Text>
<Text style={{
fontSize: 18,
fontWeight: "800",
fontFamily: 'Gill Sans',
color: '#000',
}}>
{item.providerService}
</Text>
</View>
<View style={{ alignItems: "flex-end", justifyContent: "center", flex: 1 }}>
<Icon style={{ marginRight: 20 }}
name={`ios-heart${fav ? "" : "-empty"}`}
size={35} color="#f00"
onPress={() => {
const currentUser = firebase.auth().currentUser.uid;
firebase.database().ref(`favorites/${currentUser}/${item.ProviderId}`).remove().then(() => alert("Removed"))
}}
/>
</View>
</View>
</View>
</TouchableOpacity>
</ScrollView>
)
}
}
keyExtractor={(item, index) => index.toString()}
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
},
});
export default UserFavorites;
You are removing the item from firebase but not from the flatlist's data source this.state.favorites, add a function that'll you call after removing the item from firebase.
_onRemove = (_item) => {
this.setState({
favorites: this.state.favorites.filter(item => item.ProviderId !== _item.ProviderId)
});
}
Pass the item you want to delete to the function in your flatlist
renderItem={({ item }) => {
return ....
//scrollview code
<Icon style={{ marginRight: 20 }}
name={`ios-heart${fav ? "" : "-empty"}`}
size={35} color="#f00"
onPress={() => {
const currentUser = firebase.auth().currentUser.uid;
....
// firebase code
this._onRemove(item);
}
/>
....
//rest of the code
}}

Categories