Skip to content

Instantly share code, notes, and snippets.

@pflevy
Created September 8, 2019 13:50
Show Gist options
  • Save pflevy/3ab3668b062812252f7d0c0a8279774d to your computer and use it in GitHub Desktop.
Save pflevy/3ab3668b062812252f7d0c0a8279774d to your computer and use it in GitHub Desktop.
Creating custom react hooks. Real-time firebase database entry listener example. Custom hook file.
import { useEffect, useState } from "react";
import firebase from "./database";
export const useDatabaseEntry = entry => {
const [data, setData] = useState([]);
useEffect(() => {
const ref = firebase.database().ref(entry);
ref.on("value", snapshot => {
const array = [];
// For each data in the entry
snapshot.forEach(el => {
// Push the object to the array
// If you also need to store the unique key from firebase,
// You can use array.push({ ...el.val(), key: el.key });
array.push(el.val());
});
setData(array);
});
// Clean-up function
return () => ref.off("value");
}, [entry]);
return data;
};
@jelizarovas
Copy link

Updated for v9

import { useEffect, useState } from "react";
import { database } from "../config/firebase";
import { ref as databaseRef, onValue, off } from "firebase/database";

export const useDatabaseEntry = (entry) => {
  const [data, setData] = useState([]);
  useEffect(() => {
    const ref = databaseRef(database, entry);
    onValue(ref, (snapshot) => {
      const array = [];
      // For each data in the entry
      snapshot.forEach((el) => {
        // Push the object to the array
        // If you also need to store the unique key from firebase,
        // You can use array.push({ ...el.val(), key: el.key });
        array.push(el.val());
      });
      setData(array);
    });
    // Clean-up function
    return () => off(ref);
  }, [entry]);

  return data;
};

@odtmusisi19
Copy link

why is there still undefined value

@odtmusisi19
Copy link

can you fix

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment