Reputation: 486
Hello I'm completely new to firebase and I would like to know how can I remove ad by using title (or atleast a key?)
This is how I managed to transfer firebase data to array :
componentDidMount(){
firebase.database().ref('/ads').on('value', (snapshot) =>{
var list = []
snapshot.forEach((child)=>{
list.push({
key: child.key,
title:child.val().title,
details: child.val().details
})
})
this.setState({adlist:list})
})
}
This is how I displayed on the FlatList (display works):
<FlatList
data={this.state.adlist}
keyExtractor={(item)=>item.title}
renderItem={({item})=>{
return(
<TouchableOpacity OnPress ={()=>deleteAd(item.title)}>
<View style={styles.container_2}>
<Text style={styles.text_style1}>{item.title}</Text>
<Text>{item.details}</Text>
</View>
</TouchableOpacity>
)}}/>
The function that I made to delete it from firebase
DeleteAds = (title)=>{
dispatch(deleteAd(title));
}
That's leads to this function
export const deleteAd = (title) => {
return(dispatch)=>{
firebase.database().ref('/ads/' + title).remove();
}
My firebase database looks like this:
When I click the button it's doesn't delete from firebase nor from array .Basically nothing happens.
I will greateful if you find the way to improve my delete function or maybe how I should pass firebase data to array so I could able to delete with a key.
Upvotes: 2
Views: 2235
Reputation: 598728
You're trying to delete the node by it's title. So if you delete the first node, with title dfdsd
, you're deleting the path /ads/dfdsd
, which doesn't exist.
To delete a node, you need to know its key. So you should:
deleteAd
function, instead of the title.In code:
<FlatList
data={this.state.adlist}
keyExtractor={(item)=>item.key}
renderItem={({item})=>{
return(
<TouchableOpacity OnPress ={()=>deleteAd(item.key)}>
<View style={styles.container_2}>
<Text style={styles.text_style1}>{item.title}</Text>
<Text>{item.details}</Text>
</View>
</TouchableOpacity>
)}}/>
You'll note I also modified the keyExtractor={(item)=>item.key}
, since that should probably also be based on the key of the node instead of its title.
Upvotes: 1