Reputation: 952
I want to pass an object to a React component. This object is the state of the parent element, which updates dynamically with updates from firebase. However, when I pass this object to the component and try accessing its value, I am getting undefined.
When I try to log this object in console, it show the key value pair with Value below was just evaluated now
. How do I access the attributes of this object ?
State of the parent
state = {
isSignedIn: false,
userVal: {},
cards: {},
coin: 0,
room_id: 0
};
Object getting updated
db.collection("users").doc(this.state.userVal.uid).onSnapshot(query => {
let q = query.data();
this.setState({ room_id: q.room_id, coin: q.coins });
for (const key in q) {
if (key !== "room_id" && key !== "name" && key !== "coins" && key !== "email" && key !== "no") {
let temp = this.state.cards;
temp[key] = q[key];
this.setState({ cards: temp });
}
}
})
Object passed to the component
<Cards id={this.state.userVal.uid} room_id={this.state.room_id} cards={this.state.cards} />
this.state.cards
is the problematic one
Upvotes: 0
Views: 77
Reputation: 1161
It's because the scope for this is undefined. You need to pass it through with ES6 arrow functions.
db.collection("users").doc(this.state.userVal.uid).onSnapshot(query => {
let q = query.data();
this.setState({ room_id: q.room_id, coin: q.coins });
q.forEach((key) => {
if (key !== "room_id" && key !== "name" && key !== "coins" && key !== "email" && key !== "no") {
let temp = this.state.cards;
temp[key] = q[key];
this.setState({ cards: temp });
}
})
})
Try it this way.
Upvotes: 1