Reputation: 45
My delete button, and create button wont work, I keep getting this error:
uncaught error:reference.child failed: first argument was an invalid path
import React, { Component } from 'react';
import { View, Text, StyleSheet, Button, TextInput, TouchableOpacity, selectedId } from 'react-native';
import firebase from './firebase';
export default class App extends Component {
carDatabase = firebase.database().ref('car');
state = { cars: {}, selectedId: '' }
// Read
componentDidMount() {
this.carDatabase.on('value', cars => {
const carsJSON = cars.val();
this.setState({ cars: carsJSON === null ? {} : carsJSON });
})
// this.carDatabase.push({color: 'yellow'})
}
// Create
create() {
this.carDatabase.push({color: 'yellow'})
this.setState({selectedId: ''})
}
// Update
update() {
this.carDatabase.child(this.state.selectedId).set({color: 'blue'})
this.setState({selectedId: ''})
}
// Delete
deleteCar() {
if(this.state.selectedId === '') {
return;
}
// firebase.database().ref('car/').remove
this.carDatabase.child(this.state.selectedId).set(null)
this.setState({selectedId: ''})
}
render() {
return (
<View style={styles.container}>
<TextInput value={this.state.selectedId} style={styles.textInput}></TextInput>
<Button title="create" onPress={() => this.create()}></Button>
<Button title="update" onPress={() => this.update()}></Button>
<Button title="delete" onPress={() => this.deleteCar()}></Button>
{
Object.keys(this.state.cars).map( ( index) =>
<TouchableOpacity key={index} onPress={() => this.setState({ selectedId})}>
<Text>{JSON.stringify(this.state.cars[index])}</Text>
</TouchableOpacity>
)
}
{/* <Text>{JSON.stringify(this.state.cars, null, 2)}</Text> */}
</View>
);
}
}
const styles = StyleSheet.create({
textInput: {
backgroundColor: 'green',
height: 30,
width: '100%'
},
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center'
}
});
Upvotes: 1
Views: 99
Reputation: 45
Object.keys(this.state.cars).map( (carId, index) =>
this.setState({ selectedId: carId})}>
{${carId}: ${JSON.stringify(this.state.cars[index])}
}
Upvotes: 1
Reputation: 598728
It looks like this.state.selectedId
contains something that is not a valid path in your database. You can find out what that actually is by logging the value before you use it. For example:
deleteCar() {
console.log(this.state.selectedId)
this.carDatabase.child(this.state.selectedId).set(null)
this.setState({selectedId: ''})
}
Most likely it seems that this.state.selectedId
is null or empty. Right now you're only checking for an empty string, so you might have better results if you do this instead:
deleteCar() {
if (this.state.selectedId && this.state.selectedId.length) {
this.carDatabase.child(this.state.selectedId).set(null)
this.setState({selectedId: ''})
}
}
Upvotes: 1