this might not be an issue with the mapping itself but i've read some data from my firebase realtime database into my sate and i'm trying to pass it as props then map it in a subsequent component.
I am getting the following error, I am using an android emulator:
TypeError: undefined is not a function (near ...'this.props.notes.map'...)
app.js (where I update the state)
state = {
loggedin: false,
notes: [
{
id: 1,
text: "mow the lawn",
author: "dean",
time: "10am"
},
{
id: 2,
text: "feed the dog",
author: "sam",
time: "2pm"
}
]
}
//passing props to notes component
<Notes style={styles.notes} notes={this.state.notes} />
updateNotes = async () => {
console.log("grabbing new notes");
const snapshot = await firebase.database().ref('Users/Notes').once('value');
console.log(snapshot.val())
this.setState({ notes: snapshot.val() });
};
my Notes component where I map the props
renderCondition =()=>{
if(this.state.Deleted === false){
return(
<View>
{this.props.notes.map(note => (
<View
style={styles.note}
key={note.author}
id={note.id}
>
<Text style={styles.noteHeader}>{note.author}</Text>
<Text style={styles.noteText}>{note.text}</Text>
<Text style={styles.noteTime}>{note.time}</Text>
<Button title= 'X' onPress={() => this.setState({Deleted:true}) }></Button>
</View>
))}
</View>
)
}
return(
<View>
<Text>are you sure you want to delete this note?</Text>
<Button title="Yes"></Button>
<Button onPress ={()=>{this.setState({Deleted:false})}} title="No"></Button>
</View>
)
}
render() {
return (
<View>
{this.renderCondition()}
</View>
);
}
You have to check whether the notes have been passed down or whether they are undefined or null. JavaScript is not going to map an undefined object.
Try the following code:
{this.props.notes && this.props.notes.map(note => (
// do stuff with each note...
))}
This will run the .map function only if the notes are neither undefined nor null.
So my issue was that I needed to update my notes state by making sure it was an array. I had mistakenly simply updated it as an object and then attempted to map the object. Here is my solution.
from this
updateNotes = async () => {
console.log("grabbing new notes");
const snapshot = await firebase.database().ref('Users/Notes').once('value');
console.log(snapshot.val())
this.setState({ notes: snapshot.val() });
};
to this
updateNotes = async () => {
console.log("grabbing new notes");
const snapshot = await firebase.database().ref('Users/Notes').once('value');
console.log(snapshot.val())
this.setState({ notes: [snapshot.val()] });
};
Related
I want to read data from firebase realtime database.
I want to fix my "function readData()"
like,
If I use this funcion, I want to read my data, without enter "username".
for example, I created this,
username:hello,
email:hello#gmail.com
and If I press "read data" button, (without enter 'username')
I want to read recent data. (username and email both)
please help me!
this is my app.js
import { StatusBar } from 'expo-status-bar';
import { useState } from 'react';
import { Button, button, StyleSheet, Text, TextInput, View } from 'react-native';
import { ref, set, update, onValue, remove } from "firebase/database";
import { db } from './components/config';
export default function App() {
const [username, setName] = useState('');
const [email, setEmail] = useState('');
function createData() {
set(ref(db, 'users/' + username), {
username: username,
email: email
}).then(() => {
// Data saved successfully!
alert('data created!');
})
.catch((error) => {
// The write failed...
alert(error);
});
}
function update() {
set(ref(db, 'users/' + username), {
username: username,
email: email
}).then(() => {
// Data saved successfully!
alert('data updated!');
})
.catch((error) => {
// The write failed...
alert(error);
});
}
function readData() {
const starCountRef = ref(db, 'users/' + username);
onValue(starCountRef, (snapshot) => {
const data = snapshot.val();
setEmail(data.email);
});
}
return (
<View style={styles.container}>
<Text>firebase</Text>
<TextInput value={username} onChangeText={(username) => {setName(username)}} placeholder='Username' style={styles.TextBoxes}></TextInput>
<TextInput value={email} onChangeText={(email) => {setEmail(email)}} placeholder='Email' style={styles.TextBoxes}></TextInput>
<Button title='create data' onPress={createData}></Button>
<Button title='update data' onPress={update}></Button>
<Button title='read data' onPress={readData}></Button>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
TextBoxes: {
width:'90%',
fontSize:18,
padding:12,
backgroundColor:'grey',
marginVertical:10,
}
});
I understand you want to call last username by default if username is empty.
For this, you can define lastUserName state and call it if username is empty, for example;
const [lastUserName, setLastUserName] = useState('');
readData() ,
function readData() {
const starCountRef = ref(db, 'users/' + username !== '' ? username : lastUserName);
onValue(starCountRef, (snapshot) => {
const data = snapshot.val();
setEmail(data.email);
});
}
Then, view should be like that;
<View style={styles.container}>
<Text>firebase</Text>
<TextInput value={username}
onChangeText={(username) => {
setName(username)
setLastUserName(username) // add this line
}
}
placeholder='Username' style={styles.TextBoxes}></TextInput>
<TextInput value={email} onChangeText={(email) => {setEmail(email)}} placeholder='Email' style={styles.TextBoxes}></TextInput>
<Button title='create data' onPress={createData}></Button>
<Button title='update data' onPress={update}></Button>
<Button title='read data' onPress={readData}></Button>
</View>
Note : If you want to keep this state in global use Redux.
Note: Use localStorage if you want the application to run on the same state after closing and reopening. see: https://github.com/react-native-async-storage/async-storage
Im displaying some firebase data in a flatlist and im having trouble with the keyExtractor, I keep having the error:
undefined is not an object (evaluating "item.id")
I have added an id field to all my data in firebase and made sure they were a string but it's still not recognizing it as an id.
function Squad() {
const [gk, setGk] = useState([]);
useEffect(() => {
db.collection('squad').orderBy('position').get().then(snapshot => {
const gkData = snapshot.map(doc => {
const playerObject = doc.data();
return { name: playerObject.name, number: playerObject.number, id: playerObject.id };
});
setGk(gkData);
console.log(setGk);
});
}, []);
const Item = ({ name, number }) => (
<View style={styles.item}>
<Text style={styles.itemText}>{number} - {name}</Text>
</View>
);
const renderItem = ({ item }) => (
<Item name={item.name} number={item.number} />
)
return(
<View>
<View style={globalStyles.bar}>
<Text style={globalStyles.barText}>goalkeeper</Text>
</View>
<FlatList
data={setGk}
renderItem={renderItem}
keyExtractor={item => item.id}
/>
</View>
)
}
The data you are passing into the Flatlist is the setter function! You want to pass in ‘gk’ not ‘setGk’
I'm building a barcode reader app that scans that qr code and then takes data and is used as a key to fetch an object from firebase. In order the data to be used as a key I need to pass through another screen but when I check console log it's cameback that the scanned key is undefined.
The itself barcode scanner works perfectly.
Barcode class :
export class BarCodeScannerScreen extends Component{
state = {
CameraPermissionGranted: null,
}
async componentDidMount() {
// Ask for camera permission
const { status } = await Permissions.askAsync(Permissions.CAMERA);
this.setState({ CameraPermissionGranted: status === "granted" ? true : false });
};
barCodeScanned = ({ data }) => {
//Access the Data
alert(data); // shows the scanned key
this.props.navigation.navigate('Info', {
item: data, }); // but then it's dissapears in here.
};
render(){
const { CameraPermissionGranted } = this.state;
if(CameraPermissionGranted === null){
// Request Permission
return(
<View style={styles.container}>
<Text>Please grant Camera permission</Text>
</View>
);
}
if(CameraPermissionGranted === false){
// Permission denied
return (
<View style={styles.container}>
<Text>Camera Permission Denied.</Text>
</View>
);
}
if(CameraPermissionGranted === true){
// Got the permission, time to scan
return (
<View style = {{
flex: 1,
justifyContent: 'center',
alignItems: 'center',
}}>
<BarCodeScanner
onBarCodeScanned = {this.barCodeScanned }
style = {{
height: DEVICE_HEIGHT/1.1,
width: DEVICE_WIDTH,
}}
>
</BarCodeScanner>
</View>
);
}
}
}
Here is my Info screen that receives the information :
export default class InfoScreen extends Component {
constructor(props){
super(props);
this.state={
productlist:[],
scannedkey: this.props.route.params.item
} }
async componentDidMount(){
firebase.database().ref(`product/${ this.state.scannedkey}`).on(
"value",
(snapshot) => {
var list = [];
snapshot.forEach((child) => {
list.push({
key: child.key,
title: child.val().title,
//details: child.val().details,
//price: child.val().price
});
});
this.setState({ productlist: list });
},
(error) => console.error(error)
);
}
componentWillUnmount() {
if (this.valuelistener_) {
this.valueRef_.off("value", this.valuelistener_)
}}
render() {
console.log(this.state.scannedkey); // console log shows that scanned key is undefined
return(
<View style={styles.container}>
<Text>Hey</Text>
<Text>{this.state.productlist.title}</Text>
</View>
);}}
App.js
export default function App() {
const Drawer=createDrawerNavigator();
return (
<Provider store={store}>
<NavigationContainer>
<Drawer.Navigator initialRouteName="Barcode">
<Drawer.Screen name="Barcode" component={BarCodeScannerScreen} />
<Drawer.Screen name="Info" component={InfoScreen} />
</Drawer.Navigator>
</NavigationContainer>
</Provider>
);
}
I ussualy use function components to navigate through but with class components it's a little tricky for me. Perhaps I missed something?
So far I 've tried :
this.props.navigation.navigate('Info', {
item: JSON.stringify(data) , });
And it didn't work.
I will be grateful for your help.
Try to use item directly from props, not from state
in your componentDidMount call where you supply from state the scannedKey, supply it from props
firebase.database().ref(`product/${this.props.route.params.item}`)....
you are also calling this.props instead of props directly in your state inside your constructor, which have direct access to it, that's why you can call super(props) and not super(this.props), I am not sure if this is the issue, but in react docs says don't copy props to state because they get ignored, and it's bad practice my friend.
check this link, in the big yellow note what I am reffering to
https://reactjs.org/docs/react-component.html#constructor
I'm unable to have my component render the value from events[0]. I've tried putting the data array in the .then block but the scoping gets screwed up. Since firebase requests are async, how can I make the whole component render only when I receive my data from firebase?
Finalized.js
const Finalized = () => {
let events = [];
firebase
.database()
.ref("events/arts/" + 2 + "/name")
.once("value")
.then((snapshot) => {
events.push(snapshot.val());
});
let data = [{
time: "09:00",
title: "Event 1",
description: <Text>{events[0]}</Text>, // {events[0]} has no value returned
}];
return (
<View style={styles.container}>
<Timeline style={styles.list} data={data} />
</View>
);
};
You can use a state called events instead of the variable.
Here is how to do it...
const [events, setEvents] = useState([]);
const Finalized = () => {
firebase
.database()
.ref("events/arts/" + 2 + "/name")
.once("value")
.then((snapshot) => {
setEvents(snapshot.val());
});
let data = [{
time: "09:00",
title: "Event 1",
description: <Text>{events[0]}</Text>,
}];
return (
<View style={styles.container}>
<Timeline style={styles.list} data={data} />
</View>
);
};
How to delete a image in firebase storage using the url of the image in react native?
this is the structure of the data
list {
["https://firebasestorage.googleapis.com/v0/b/testes-109.appspot.com/o/photos%2FmdWs20BYhSdR4XIePdpBL9szC7i2%2F79337645-7aa6-4fa3-ab29-9dae6f41bc6?alt=media&token=a9cc2795-f118-485c-94b9-cdf0c083eb2a", "https://firebasestorage.googleapis.com/v0/b/testes-109.appspot.com/o/photos%2FmdWs20BYhSdR4XIePdpBL9szC7i2%2F79337645-7aa6-4fa3-ab29-9dabe6f41bc6?alt=media&token=a9cc2795-f118-48c-94b9-cdf0c83eb2a", ],
}
i tried this
<FlatList
data={list}
renderItem={({ item, index }) => {
return (
<View >
<TouchableOpacity onPress={() => this.deleteImage(item)} >
<Image source={{ uri: item }} style={{ width:100, height: 100 }} />
</TouchableOpacity >
</View>
)
}}
/>
deleteImage = (item) => {
alert(item)
var desertRef = item;
desertRef.delete()
.then(function() {
console.log('File deleted successfully')
}).catch(function(error) {
console.log('Uh-oh, an error occurred!')
});
}
but got this error
desertRef.delete is not a fuction. (in 'desertRef.delete()', 'desertRef.delete' is undefined
create storage object with your firebaseConfig
const app = initializeApp(firebaseConfig);
const storage = getStorage(app);
export default storage;
You need to use the following function to delete it from storage.
import { deleteObject, ref } from "firebase/storage";
import storage from "<your storage file path where you export it>";
export const deleteFromStorage = (file: string | undefined) => {
if (file) {
let pictureRef = ref(storage, file);
deleteObject(pictureRef)
.then(() => {
alert("Picture is deleted successfully!");
})
.catch((err) => {
console.log(err);
});
}
}