I'm trying to load data from my firebase after I checked if a user is signed in. I tried to do it with a promise, but I get this error
whenAuth.then is not a function
I tried also to load the data from componentDidMount()
and render()
methods, but the query didn't wait for the initialisation of the user.
componentWillMount() {
let whenAuth =
firebase.auth().onAuthStateChanged((user) => {
const userProfile = firebase.auth().currentUser;
if(user){
this.setState({
authenticated: true,
name : userProfile.displayName,
email : userProfile.email,
uid : userProfile.uid,
})
} else {
this.setState({
authenticated: false,
})
return <Redirect to="/"/>
}
})
whenAuth.then(()=>{
const previousCards = this.state.cards;
firebase.database().ref().child('app').child('cards')
.orderByChild('uid').equalTo(this.state.uid)
.once('value', snap => {
snap.forEach(childSnapshot => {
previousCards.push ({
id: childSnapshot.key,
cardDesc: childSnapshot.val().cardDesc,
cardPreis: childSnapshot.val().cardPreis,
cardHeading: childSnapshot.val().cardHeading,
cardBewertung: childSnapshot.val().bewertung,
cardImage: childSnapshot.val().imageUrl,
standOrt: childSnapshot.val().ort,
imageArr: childSnapshot.val().imageArr,
})
this.setState ({
cards: previousCards,
})
})
})
})
}
Thanks in advance for any help
You method does not return a promise. So the solution is to call your logic in the callback.
myMethod() {
const previousCards = this.state.cards;
firebase.database().ref().child('app').child('cards')
.orderByChild('uid').equalTo(this.state.uid)
.once('value', snap => {
snap.forEach(childSnapshot => {
previousCards.push ({
id: childSnapshot.key,
cardDesc: childSnapshot.val().cardDesc,
cardPreis: childSnapshot.val().cardPreis,
cardHeading: childSnapshot.val().cardHeading,
cardBewertung: childSnapshot.val().bewertung,
cardImage: childSnapshot.val().imageUrl,
standOrt: childSnapshot.val().ort,
imageArr: childSnapshot.val().imageArr,
})
this.setState ({
cards: previousCards,
})
})
})
}
componentWillMount(){
let whenAuth = firebase.auth().onAuthStateChanged((user)=>{
const userProfile = firebase.auth().currentUser;
if(user){
this.setState({
authenticated: true,
name : userProfile.displayName,
email : userProfile.email,
uid : userProfile.uid,
})
} else {
this.setState({
authenticated: false,
})
return <Redirect to="/"/>
}
// --> your function ends here
this.myMethod();
})
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.