Amanda K Amanda K - 1 month ago 27
React JSX Question

Get user object properties from Firebase in React

I have a user db in Firebase that uses the unique user id as the Key and within that key/value pairs like name: 'jane doe', email: 'jane@doe.com', etc. What I want to do is map the object and get the key values within. I'm able to get the Key (user id), but not the object key value pairs. Here's my code:

export default class Home extends Component {

constructor(props) {
super(props);

var users = {};
this.state = { users };
}

componentDidMount() {
const dbRoot = firebaseDb.database().ref().child('users');

dbRoot.on('value', snap => {
const dbUsers = snap.val();

this.setState({
users: dbUsers
});
});
}


render() {
return (
<div>
<div>
{Object.keys(this.state.users).map(function(user, i) {
return <div key={i}>Key: {user}, Value: {user.name}</div>;
})}
</div>
</div>);

}

}


user.name comes back undefined. I've tried using this.state.users.name but I get a "state is undefined" message. Can someone point me in the right direction. Thanks!

Answer

You have two main problems with your code. The first is that you cannot access this.state inside the callback of your map() function because this is bound to that function and not to the whole class. There are a couple of ways to keep the this variable bound to the class but the cleanest way is to use the Arrow function syntax.

Once you do that, you will still have a problem. You are using Object.keys which will only map over the keys of your result, but you are treating it as if it will pass the whole user object to the function. In order to access the user object inside of your callback function, you will need to use the bracket notation with the key.

With those two things in mind, your code should look something like this:

{Object.keys(this.state.users).map(key => {
    return <div key={key}>Key: {key}, Value: {this.state.users[key].name}</div>;
})}