Episode 44 of 44

Retrieving Posts from Firebase

Fetch blog posts from Firebase — GET data from the Realtime Database, transform the response, and display posts in the blog list.

Retrieving Posts from Firebase

Now that you can save posts to Firebase, let us fetch and display them on the home page. Firebase returns data in a specific format that needs to be transformed into an array.

Fetching Data

// Home.vue
export default {
    data() {
        return { blogs: [] };
    },
    created() {
        this.$http.get('https://your-project.firebaseio.com/posts.json')
            .then(response => {
                return response.json();
            })
            .then(data => {
                const blogsArray = [];
                for (let key in data) {
                    data[key].id = key;
                    blogsArray.push(data[key]);
                }
                this.blogs = blogsArray;
            });
    }
};

Transforming Firebase Data

// Firebase returns an object:
{
    "-NaB1cD2eF3gH4iJ": { title: "Post 1", ... },
    "-NaB5kL6mN7oP8qR": { title: "Post 2", ... }
}

// We need an array:
[
    { id: "-NaB1cD2eF3gH4iJ", title: "Post 1", ... },
    { id: "-NaB5kL6mN7oP8qR", title: "Post 2", ... }
]

Firebase stores data as a nested object with auto-generated keys. The for...in loop converts each entry into an array element, attaching the Firebase key as the id.

Displaying the Posts

<template>
    <div id="blog-list">
        <div v-for="blog in blogs" :key="blog.id" class="blog-card">
            <router-link :to="'/blog/' + blog.id">
                <h3>{{ blog.title | capitalize }}</h3>
            </router-link>
            <p>{{ blog.content | snippet }}</p>
            <p class="meta">by {{ blog.author }}</p>
            <div class="categories">
                <span v-for="cat in blog.categories" :key="cat">{{ cat }}</span>
            </div>
        </div>
    </div>
</template>

Single Post Page

// SingleBlog.vue
created() {
    const id = this.$route.params.id;
    this.$http.get('https://your-project.firebaseio.com/posts/' + id + '.json')
        .then(response => {
            this.blog = response.body;
        });
}

To fetch a single post, append the Firebase key to the URL: /posts/key.json.

The Complete Data Flow

AddBlog Component                    Firebase DB                    Home Component
─────────────────                ──────────────────             ─────────────────
Form fields (v-model)                                          
    ↓                                                          
POST /posts.json ──────────→     Stores the data     ←──────── GET /posts.json
    ↓                                  ↑                           ↓
$router.push('/')                      │                     Transform to array
                                       │                           ↓
                                       │                     Render with v-for

Series Wrap-up

Congratulations! You have completed the Vue JS 2 Tutorial. You have learned:

  • The Vue instance, data binding, events, and computed properties
  • Components, props, slots, and component communication
  • The Vue CLI and single-file components
  • Custom directives, filters, and mixins
  • Vue Router with hash and history modes
  • HTTP requests and Firebase integration

Key Takeaways

  • Firebase GET returns an object — transform it into an array with for...in
  • Attach the Firebase key as an id property for routing and identification
  • Fetch single records with /collection/key.json
  • The full blog app demonstrates Vue fundamentals: components, routing, HTTP, and data binding