i am building a simple React app where i collect data from a Firebase realtime database and push it as an array (memberArr) into the component state via setState:
this.setState({members: memberArr})
When I log the state in the render() method, I see the contents of the array. In the React Dev Tools the state is also filled as expected.
If I now want to access the contents of the array (e.g. with this.state.members[0]) the console returns undefined.
I initialize the state like this:
constructor(props) {
super(props);
this.state = {
members: [],
};
}
My whole componentDidMount() method looks like this:
componentDidMount() {
const membersRef = firebase.database().ref(`${groupName}/members`);
membersRef.on('value', (data) => {
const memberArr = [];
data.forEach(function(snapshot){
//Gets name of member
var memberName = snapshot.val().name;
//Gets UID of member
var memberKey = snapshot.key;
//Get expenses from fetched member. When ready call function to push everything as array into component state.
this.getExpensesFromUser(memberKey).then(function(data) {
pushArray(data)
});
function pushArray(memberExpense) {
memberArr.push([memberName, memberKey, memberExpense])
};
//This works:
//memberArr.push([memberName, memberKey])
}.bind(this));
this.setState({members: memberArr})
});
}
On a side note: If I avoid calling
this.getExpensesFromUser(memberKey).then(function(data) {
pushArray(data)
});
and only use the following to push the name and key of the members:
memberArr.push([memberName, memberKey])
everything works as expected. console.log(this.state.members[0][0]) returns the name of the first member after the render() method gets triggered due to setState.
Do you have any tips for me?
this.getExpensesFromUser(memberKey)is async and you're setting the state before actually receiving the values, so your state is always []pushArray(data)in the.then(data)try doingthis.setState({members: [...this.state.members, data]