javascriptreactjsfirebase-realtime-database

Get data from Firebase Database Structure and Show it in multiple elements


I try to get all the datas from a specific section on my Firebase Database and show the information into a list-bar.

Here is the code:

import React from 'react'
import { RiDeleteBin6Line } from "react-icons/ri";
import { FaExchangeAlt } from "react-icons/fa";
import { ref, child, get } from 'firebase/database'
import { getDatabase } from 'firebase/database'
import { getAuth } from "firebase/auth";

export const CardDateList = ( ) => {

    const dbRef = ref(getDatabase());

    const auth = getAuth();
    const user = auth.currentUser.reloadUserInfo.localId;

    if (user !== null) {

        get(child(dbRef, `locations/identify/${user}`)).then((snapshot) => {
          if (snapshot.exists()) {
  
        let LocationName = (snapshot.val().name);

        get(child(dbRef, `locations/public/${LocationName}/availabledates/`)).then((snapshot) => {

          var DataDateList =[];
          
            snapshot.forEach(childSnapshot => {
              DataDateList.push(childSnapshot.val());
            });
          
          console.log(DataDateList);

  return (
    <div className='container_date_element'>
        <label key={DataDateList.date}>
            <div className='container_date_list_element' id={DataDateList.date}>
                <form className='form_date_list_element'>
                    <div className='list_element'>
                        <label>{DataDateList.date}</label>
                        <br></br>
                        <input></input>
                    </div>
                    <div className='list_element'>
                        <label>{DataDateList.genre}</label>
                        <br></br>
                        <input></input>
                    </div>
                    <div className='list_date_button'>
                          <button><FaExchangeAlt/></button>
                          <button><RiDeleteBin6Line/></button>
                    </div>
                </form>
            </div>
        </label>
    </div>
  );
})


} else {
    console.log("No data available");
  }

  
}).catch((error) => {
  console.error(error);
});


  };
};

My structure is looks like this on Firebase:

Structure Firebase Database

How can I get the data from the 4 different dates (availabledates) and pass the list to the list-bar?

the console.log is showing this:

enter image description here


Solution

  • Since the console.log shows the correct information, you're already fetching the right information and processing it correctly. The problem seems to be in getting that information to show in the UI.

    When you load data dynamically, you need tell React that it needs to refresh the UI. The common way to do that is to update the state of the component, which you can do with useState.