In the initialize file, I code like this.
import { initializeApp } from 'firebase/app';
import { getDatabase, ref, child, get } from "firebase/database";
const config = {
};
const app = initializeApp(config);
const db = getDatabase(app);
const dbRef = (ref(db));
get(child(dbRef, "shop_data")).then((snap) => {
console.log(snap.val())
})
export {dbRef};
From here, I receive one result from console.log
Now, in my Store component, I only put the get() function in
import '../css/StoreSelectable.css';
import { dbRef } from '../js/firebase_init';
import { getDatabase, ref, child, get } from "firebase/database";
function StoreSelectable(){
const getStore = () => {
get(child(dbRef, "shop_data")).then((snap) => {
console.log(snap.val())
})
return;
}
return(
<div className="Store-Selectable">
<table id="place_option" align="center" style={{tableLayout: 'fixed'}} className="radioButtons collapseBorder">
<tbody>
{getStore()}
</tbody>
</table>
</div>
);
}
export default StoreSelectable;
Now, firebase function fires twice.
Edit 10/6/2022 I tried useEffect, but it still gets the data twice. I really do not want to use Firestore since I have to rewrite a lot of codes. What should I do in this situation?
import "../css/StoreSelectable.css";
import { dbRef } from "../js/firebase_init";
import { getDatabase, ref, child, get } from "firebase/database";
import { useEffect, useState } from "react";
function StoreSelectable() {
const pin = {
TestiKirppis: ["Jarii1", "spr1234", "6899bc73da4ace09"],
Vaasa: ["D0ED5D57F47580F2", "spr9876", "Vas183"],
Seinäjoki: ["a1a1a1a1a1a1a1a1", "spr9999", "Seina19"],
Kokkola: ["regT863", "spr0000", "b4b8bb4ceeaa2aee"],
};
const [count, setCount] = useState([]);
useEffect(() => {
const getStore = () => {
get(child(dbRef, "shop_data")).then((snap) => {
let val = snap.val();
Object.keys(val).forEach((key) => {
setCount((count) => [...count, val[key].name]);
})
});
}
getStore();
}, []);
return (
<div className="Store-Selectable">
<table
id="place_option"
align="center"
style={{ tableLayout: "fixed" }}
className="radioButtons collapseBorder"
>
<tbody>{count.map((data) => {return (<p>{data}</p>)})}</tbody>
</table>
</div>
);
}
export default StoreSelectable;