Reputation: 97
I am trying to render data from realtime firebase in react.
In the console, I am getting the error that
data.component.js:10 Uncaught TypeError: firebase__WEBPACK_IMPORTED_MODULE_2_.default.child is not a function
pointing to the line
Database.child("L1").on("value", (snapshot) => {
of the below code.
Any thoughts on how I can rectify?
Below is a copy of my code
const Data = () => {
const [data, setData] = useState ({});
useEffect (() => {
Database.child("L1").on("value", (snapshot) => {
if (snapshot.val() !== null) {
setData({ ...snapshot.val() });
} else {
setData({});
}
});
return () => {
setData ({});
};
}, []);
return (
<div style={{marginTop: "100px"}}>
<table className="styled-table">
<thead>
<tr>
<th style={{textAlign: "center"}}> L4 </th>
<th style={{textAlign: "center"}}> L4 </th>
</tr>
</thead>
<tbody>
{Object.keys(data).map((id, index) => {
return (
<tr key={id}>
<th scope="row">{index +1}</th>
<td>{data[id].result_1}</td>
<td>{data[id].result_2}</td>
<td>{data[id].result_3}</td>
<td>{data[id].result_4}</td>
</tr>
)
} )}
</tbody>
</table>
</div>
);
};
export default Data
Firebase Config
import { initializeApp } from 'firebase/app';
import { Database, getDatabase } from "firebase/database";
const firebaseConfig = {
apiKey: "",
authDomain: "",
databaseURL: "",
projectId: "",
storageBucket: "",
messagingSenderId: "",
appId: "",
measurementId: ""
};
const app = initializeApp(firebaseConfig);
const database = getDatabase(app)
export default Database;
Upvotes: 0
Views: 360
Reputation: 50860
You don't have import Database
class from Realtime Database SDK. You can just export the database
instance initialized and then use it.
// Firebase config
import { initializeApp } from 'firebase/app';
import { getDatabase } from "firebase/database";
const firebaseConfig = {...};
const app = initializeApp(firebaseConfig);
export const database = getDatabase(app)
Then use the newer functional syntax instead of older namespaced one. Try refactoring the code as shown below:
// update the path herer
import { database } from '../path/to/firebase-config.js'
const [data, setData] = useState({});
useEffect(() => {
const dbRef = ref(database, 'L1/');
onValue(dbRef, (snapshot) => {
if (snapshot.exists()) {
setData(snapshot.val());
} else {
setData({});
}
});
}, []);
You can use exists()
instead of checking if snapshot value is null (which is slightly more efficient as mentioned in the documentation)
Upvotes: 1