He estado tratando de hacer un sitio web de comercio electrónico y casi todo está hecho, excepto la parte de la base de datos. En el que tengo que buscar los datos de firebase y usarlos en la sección de productos. Obtuve los datos en variables locales, sin embargo, quiero almacenar los datos en un objeto de ámbito global, pero no funciona. Entonces, lo que básicamente quiero es obtener los datos de firebase (HECHO) y almacenarlos en un objeto de alcance global (PENDIENTE) para poder usar este objeto en otros archivos .js. Cualquier tipo de idea/consejo/ayuda/sugerencia es más que bienvenida!! ¡Gracias por adelantado!
Este es mi código: https://jsfiddle.net/kumartanwar123/gseh4coq/
O
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.6.7/firebase-app.js"; import { getAnalytics } from "https://www.gstatic.com/firebasejs/9.6.7/firebase-analytics.js"; // GLOBAL VARIABLES var name, images, prices; const firebaseConfig = { apiKey: "--", authDomain: "--", databaseURL: "--", projectId: "round-device-336118", storageBucket: "round-device-336118.appspot.com", messagingSenderId: "--", appId: "--", measurementId: "--", }; const app = initializeApp(firebaseConfig); firebase.initializeApp(firebaseConfig); class firebase_class { constructor(Images, Prices, Name) { this.Images = Images; this.Prices = Prices; this.Name = Name; } } // FIREBASE DATA FETCH firebase .database() .ref("Practice") .on("value", function (all_data) { all_data.forEach(function (current_data) { name = Object.keys(current_data.val().Name).map( (keys) => current_data.val().Name[keys] ); //In this if I use console.log(name) then it is working just fine, but not in outside the function. images = Object.keys(current_data.val().Images).map( (keys) => current_data.val().Images[keys] ); prices = Object.keys(current_data.val().Prices).map( (keys) => current_data.val().Prices[keys] ); }); }); let firebase_object = new firebase_class(images, prices, name);El problema no es dónde accede a la base de datos, sino cuándo accede a ella.
Los datos se cargan desde Firebase (y prácticamente todas las API modernas en la nube) de forma asincrónica, y su código principal (y, por lo tanto, let firebase_object = new firebase_class(images, prices, name) ) continúa ejecutándose mientras se cargan los datos. Luego, cuando los datos están disponibles, se invoca su devolución de llamada y establece images , prices y name .
Y el código que necesita los datos de Firebase debe estar dentro de la devolución de llamada o ser llamado desde allí. Asi que:
// FIREBASE DATA FETCH firebase .database() .ref("Practice") .on("value", function (all_data) { all_data.forEach(function (current_data) { name = Object.keys(current_data.val().Name).map( (keys) => current_data.val().Name[keys] ); //In this if I use console.log(name) then it is working just fine, but not in outside the function. images = Object.keys(current_data.val().Images).map( (keys) => current_data.val().Images[keys] ); prices = Object.keys(current_data.val().Prices).map( (keys) => current_data.val().Prices[keys] ); }); // 👇 let firebase_object = new firebase_class(images, prices, name); ... any use of firebase_object should be here too });También echa un vistazo a: