Using UseEffect with Firebase Realtime Database

In my current project I’m working on, I’m building up a React application. This app will replace an existing desktop, Windows-only Python 2 app that a client has had for around 8 years.

The client uses Firebase Realtime database for their existing data, and rather than try to solve their data problems, I’ll fit this data into the application using useEffect and the Firebase SDK: https://github.com/firebase/firebase-js-sdk.

Modern React + Hooks

It’s been many years since I’ve written a React application, and since then Hooks have taken over by storm. Goodbye good ole' days of componentDidMount(), hello useEffect.

Since everything is a function now, so is my new component:

export default function AwesomeComponent({awesomeProp}) {
    // ... Do extra stuff.
}

Now to run things on mount, one uses useEffect. Also, to create state, one uses useState. Here’s my full example below of using Firebase Realtime DB in useEffect

import {child, getDatabase, ref, get} from "firebase/database";

export default function AwesomeComponent({awesomeProp}) {
    const [thing, setThing] = useState(null);

    useEffect(() => {
        async function makeQuery() {
            const dbRef = ref(getDatabase());
            const result = await get(child(dbRef, "child"));
            setThing(result.val());
        }

        makeQuery();
    }, [setThing]);
}

useEffect explained.

This hook runs on page load/component mount. It takes an “effect” function, and an array of dependencies. Because I enclose over setThing, I need to pass it in as a dependency.

I have to wrap my querying in makeQuery, because async effect functions aren’t allowed. The fix is to write an async function from within the handler, then call it immediately.

From within the handler, I do the actual querying using the Firebase JS SDK. It’s out of scope here to set this up, but Firebase has excellent documentation that one should consult if needed.

Conclusion

That’s all for now! Easy update, easy to understand code.

I’m building Perview.

For updates on Perview, and email notifications when I first release a post, please subscribe.

Thank you!

 Share!

 
I run WindleWare! Feel free to reach out!

Subscribe for Exclusive Updates

* indicates required