Reputation:
export class Diet extends Component {
constructor(props) {
super(props);
this.state = {
loaded: false,
Ft: 0,
};
}
async componentDidMount() {
const id = firebase.auth().currentUser.uid;
await firebase.firestore
.collection("users")
.doc(id)
.get()
.then(function (doc) {
if (doc.exists) {
this.setState({
Ft: users.Ft,
});
} else {
alert("error");
}
});
}
Hello, I am trying to retrieve the Ft
from my Firestore document and store the value in this.state
, so afterward I can use it in an expression later on on the page, any idea on what I'm doing wrong?
Error: [Unhandled promise rejection: TypeError: _firebase.default.firestore.collection is not a function. (In '_firebase.default.firestore.collection("users")', '_firebase.default.firestore.collection' is undefined)]
Upvotes: 0
Views: 389
Reputation: 600110
I think you're looking for
async componentDidMount() {
const id = firebase.auth().currentUser.uid;
firebase.firestore()
.collection("users")
.doc(id)
.get()
.then(function (doc) {
if (doc.exists) {
this.setState({
Ft: doc.data().Ft
});
} else {
alert("error");
}
});
}
Upvotes: 1
Reputation: 2720
You can try consoling your returned data to know what firestore
is returning. Another mistake that you're doing is that you're using await
together with then/catch
and they don't work together in the same function. Run this snippet to correct the mistake and check the console for what firestore
is actually returning.
export class Diet extends Component {
constructor(props) {
super(props);
this.state = {
loaded: false,
Ft: 0,
};
}
async componentDidMount() {
const id = firebase.auth().currentUser.uid;
firebase.firestore
.collection("users")
.doc(id)
.get()
.then(function (doc) {
if (doc.exists) {
console.log(doc.data());
//As you're expecting to get Ft then you can set the state like this
this.setState({
Ft: doc.data().Ft
});
} else {
alert("error");
}
});
}}
or use try/catch
export class Diet extends Component {
constructor(props) {
super(props);
this.state = {
loaded: false,
Ft: 0,
};
}
async componentDidMount() {
const id = firebase.auth().currentUser.uid;
let fetchedData = await firebase.firestore.collection("users").doc(id).get()
try {
if(fetchedData.exists){
console.log(fetchedData.data());
//As you're expecting to get Ft then you can set the state like this
this.setState({
Ft: doc.data().Ft
});
}
} catch (error) {
alert("error", error);
}
}
}
Upvotes: 1