QuteBoy
QuteBoy

Reputation: 21

how to fetch data from firebase realtime database in react js

there I am studying to fetch data from firebase realtime database I watched various youtube videos and few posts and got this far code is kinda right and don't know where I made a mistake I would be happy if someone helps me I have attached both JSON and react code for better understanding. I was only able to fetch IDs only from the database ...

here is code

import React, { Component, Fragment } from "react";
import "bootstrap/dist/css/bootstrap.min.css";
import firebase from './firebase.js';






class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      accounts: [],
      
      users: [],
    }
  }

  componentDidMount() {
    const accountRef =  firebase.database().ref('accounts');
    accountRef.on('value', (snapshot) => {
      let accounts = snapshot.val();
      let newState = [];
      for (let account in accounts) {
        newState.push({
          id:account,
          account: accounts[account].account,
          title: accounts[account].title,
          
        })
      }
      this.setState({
        accounts:newState,
      })
    })
    const userRef = firebase.database().ref('users');
    userRef.on('value', (snapshot) => {
      let users =  snapshot.val();
      let newUserState = [];
      for (let data in users) {
        newUserState.push({
          id:data,
          account:users[data].account,
          name: users[data].name,
        })
        console.log(data)
      }
    })
  }
  

  render() {
    return (
      <Fragment >
      <section>
        <div>
          <h2>User Details</h2>
            {this.state.accounts.map( data =>
            <div key={data.id}>
              {console.log(data.title)}
              <h4 >{data.account}</h4>
              <h4 >{data.name}</h4>
                </div>
              
            )}
        </div>
        <div>
          <h2>User Apps</h2>
            {this.state.accounts.map( accounts =>
            <div key={accounts.id}>
              {/* {console.log(accounts.title)} */}
              <h4 >{accounts.id}</h4>
              <h4 >{accounts.title}</h4>
                </div>
              
            )}
        </div>
      </section>
      
        
      </Fragment>
    );
  }
}
export default App;

here is josn file structure

{
  "accounts": {
    "-Kd_teAAXcw2b5MyFPIT": {
      "apps": {
        "cuckoosnest": {
          "title": "One Flew Over The Cuckoo’s Nest"
        }
      }
    },
    "-Kd_ZCjRYSGzISxY_5Wi": {
      "apps": {
        "psycho": {
          "title": "Psycho"
        }
      }
    },
    "-Kda3ClE2i0vZzyh7uh0": {
      "apps": {
        "addams": {
          "title": "The Addams Family"
        }
      }
    },
    "-Kda8nknT6-XyJE_SjCl": {
      "apps": {
        "princess-bride": {
          "title": "The Princess Bride"
        }
      }
    },
    "-KdeN0Yk89J4l5hMJ6Ea": {
      "apps": {
        "mi": {
          "title": "Mission: Impossible"
        }
      }
    },
    "-KdWbLKO0uZ0W5LYe9gj": {
      "apps": {
        "bladerunner": {
          "title": "Blade Runner"
        }
      }
    },
    "-KdWI6HAF0_wh9-NTEpe": {
      "apps": {
        "dragontattoo": {
          "title": "The Girl With The Dragon Tattoo"
        }
      }
    },
    "-KdWPnObbAbjd9lHX___": {
      "apps": {
        "nakedgun": {
          "title": "Naked Gun"
        }
      }
    },
    "-Ke4dwlXoIBXPgB8v9Pt": {
      "apps": {
        "scarface": {
          "title": "Scarface"
        }
      }
    },
    "-Ke4YQMM3aTQ-u19uIuv": {
      "apps": {
        "fargo": {
          "title": "Fargo"
        }
      }
    }
  },
  "users": {
    "00L91c7cvUaghNmGlC0lJa9eZ102": {
      "account": "-Kd_teAAXcw2b5MyFPIT",
      "name": "Randle McMurphy"
    },
    "0YRaZC6EUrc5sc8Ab4AR7Zp7ig93": {
      "account": "-Kd_ZCjRYSGzISxY_5Wi",
      "name": "Norman Bates"
    },
    "11yVrZ6TK3ZuKpITF8UVGF4ILlC3": {
      "name": "Wednesday Addams",
      "account": "-Kda3ClE2i0vZzyh7uh0"
    },
    "2d0WRN7v3lYNc9DX02yMfLmTiIM2": {
      "name": "Inigo Montoya",
      "account": "-Kda8nknT6-XyJE_SjCl"
    },
    "39IY5AX8zfgtztbQ4RFCJ0dSsel1": {
      "name": "Ethan Hunt",
      "account": "-KdeN0Yk89J4l5hMJ6Ea"
    },
    "39VBFQdD1qNgNydJ2A6kdoVLhIc2": {
      "name": "Roy Batty",
      "account": "-KdWbLKO0uZ0W5LYe9gj"
    },
    "3ACrWNFyEVObZaWMcMmZq9C045h1": {
      "name": "Lisbeth Salander",
      "account": "-KdWI6HAF0_wh9-NTEpe"
    },
    "3C9RrP8bxAVRhRcPHNBOpc5oTo83": {
      "name": "Frank Drebin",
      "account": "-KdWPnObbAbjd9lHX___"
    },
    "3kqJLMDHO2N5APYHpv5H8VtRXoj1": {
      "name": "Tony Montana",
      "account": "-Ke4dwlXoIBXPgB8v9Pt"
    },
    "44w3em7XKfhKcSSvQVk8hJIfsBQ2": {
      "name": "Marge Gunderson",
      "account": "-Ke4YQMM3aTQ-u19uIuv"
    }
  }
}

Upvotes: 2

Views: 8596

Answers (1)

moyou
moyou

Reputation: 96

To fix the users data you need to do this

const userRef = firebase.database().ref('users');
userRef.on('value', (snapshot) => {
  let newUserState = [];
  snapshot.forEach(data => {
    const dataVal = data.val()
    newUsersState.push({
      id: data.key,
      name: dataVal.name,
      account: dataVal.account
    })
  })
})

for the accounts data i am not sure what information you are trying to add to the state.... you are trying to call .account & .title but that does not exist in the snapshot.. but either way your data is poorly structured and makes it difficult to manage

Upvotes: 4

Related Questions