DEV Community

Cover image for Using Google cloud firebase for React
Ting Chung
Ting Chung

Posted on

Using Google cloud firebase for React

I recently started an art portfolio project with Google cloud firebase and found the interface to be very developer friendly! Here is a link to their website firebase homepage

Starting a project was very easy! I logged in with my Google account, started a project and was able to host my React project within minutes. Google firebase has many great tools available as a BaaS (backend as a service). I started my project out needing a database and file storage. The real-time database has some great features. It is a NoSQL database which stores all the entries in JSON format. For more information regarding the Real-time database, go here.

Here is a picture of a sample of the database:

Real-time database sample

One of the features I love about starting a new database is that you can manually enter new entries in the firebase console. This way, when I build my React app and want to retrieve database entries, I can do it quickly. They also allow you to easily delete entries as an administrator. Also starting the configuration for your firebase app was pretty straightforward. In the firebase console, you can find the configuration by going into your settings. After you find it and put it in your React app, it should look like the following:

For this blog, I am going to focus on the real-time database. First, you need to setup the firebase database rules. The rules live in a JSON file called "database.rules.json". As an alternative, you can use the database rules in your project console and publish; however, the issue is when you start deploying your project, the "database.rules.json" file overrides what you published in your firebase console, so be careful of that. Also, what is nice about the firebase console is that you can use the Rules Playground feature to test your rules. I used that to validate that the proper reads and writes would be achieved with your rules. For more information about the rules playground, go here:

Rules Playground

For my project, I wanted all users to see the artwork; however, I wanted to restrict writes to the admin user. This can be achieved with a rule like the one below:

{
  "rules": {
    "some_path": {
      "${subpath}": {
        //
        ".write": "root.child('users').child(auth.uid).child('role').val() == 'admin'",
        ".read": true
      }
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

So breaking down the rule for write, it looks in your "users" table for the authenticated user id and checks the role of that authenticated user to see if they are called 'admin'. It's pretty simple, but you need to setup a users table in the real-time database with your related user id.
Again, make sure to test your rules to make sure they are working properly. Every setup will be different.
The last topic I wanted to cover is to perform a read to the database using React. For this, I used React/Redux to dispatch the data to my Redux store so I can use the art pieces throughout my application. For this, I used the React useEffect function to perform a once read. Here is what the code looked like:

useEffect(() => {
        function getData() {


            let artsRef = firebase.database().ref('arts/')

            return artsRef.once('value', (snapshot) => {

                const data = snapshot.val()

                dispatch({type: 'GET_ARTS', payload: data})
            })

        }
        getData()
    },[dispatch])
Enter fullscreen mode Exit fullscreen mode

As you can see, the first thing I did was create a reference to the database resource I am about to access. I called it 'arts/' After creating the reference, I use the 'once' method to get a snapshot of the data and I call snapshot.val() to get the data that was a result. After the data is captured, I perform a dispatch to Redux to put my data in my artsReducer. My artsReducer function looks like this:

export function artsReducer(state = { arts: [], requesting: false, loaded: false}, action) {
    let art;
    let arts;
    switch(action.type) {

        case 'START_REQUESTING_ARTS':

            return {
                ...state,
                arts: [],
                requesting: true,
                loaded: false
            }

        case 'GET_ARTS':

            return {
                ...state,
                arts: action.payload,
                requesting: false,
                loaded: true
            }

        default:
            return state
    }
}
Enter fullscreen mode Exit fullscreen mode

After getting the data, you can perform a map render to your React components and you should be good to go!
In my next blog, I will go over how to perform specific queries to the real-time database.
Happy coding!

Top comments (0)