How it works...

The key to understanding how Firebase works with Redux is that you need to know that Firebase uses a WebSocket to sync the data, and that means the data is streaming in real time. The way to detect data changes is by using the database.on() method.

In the fetchPhrases() action, we have three Firebase listeners:

  • database.on('child_added'): It has two functionalities. The first one brings the data from Firebase (the first time) row by row. The second functionality is to detect when a new row is added to the database and updates the data in real time.
  • database.on('child_changed'): It detects changes in existing rows. This works when we perform an update of a row.
  • database.on('child_removed'): Detects when a row is removed.

There is another method called database.once('value'), which does the same thing as child_added but returns the data in an array, and just once. That means it does not detect dynamic changes like child_added.

If you run the application, you will see this view:

The blockquotes are too big to put all of them in, but our last one is this:

Let's modify our phrases.json and add a new row:

  {
"phrases": [
{
"phrase": "A room without books is like a body without a
soul.",
"author": "Marcus Tullius Cicero"
},
{
"phrase": "Two things are infinite: the universe and human
stupidity; and
I'm not sure about the universe.",
"author": "Albert Einstein"
},
{
"phrase": "You only live once, but if you do it right, once is
enough.",
"author": "Mae West"
},
{
"phrase": "If you tell the truth, you don't have to remember
anything.",
"author": "Mark Twain"
},
{
"phrase": "Be yourself; everyone else is already taken.",
"author": "Oscar Wilde"
},
{
"phrase": "Hasta la vista, baby!",
"author": "Terminator"
}
]
}

If we go to Firebase and import the JSON again, we will see that, in real time, the data will be updated without refreshing the page:

Now, if you see an X link to remove phrases, let's remove the first one (Marcus Tullius Cicero). If you open the Firebase page in another tab, you will see that the data is being deleted in real time:

Also, if you add a new row (using textarea and input), you will see that reflected in real time:

As I mentioned before, when we add new data from our React application, instead of importing a JSON Firebase will generate unique keys for the new data. In this case for the new phrase I added, the -LJSYCHLHEe9QWiAiak4 key was created.

Even if we update a row, we can see that the change was reflected in real time:

As you can see, all the operations are easy to implement, and with Firebase we saved a lot of time that would otherwise have been spent working on a backend service. Firebase is awesome!

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.190.207.144