Amanda K Amanda K -4 years ago 214
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: '', 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) {

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

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

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

users: dbUsers

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


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

Answer Source

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>;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download