Realtime Subscriptions using Vue + Supabase
Tags: javascript, vue, webdev, database
Published: 2021-01-26 16:51:10

---
title: Realtime Subscriptions using Vue + Supabase
published: true
description: How to implement realtime subscriptions using Vue and Supabase (an open-source Firebase alternative).
tags: javascript, vue, webdev, database
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/bwmc51mn035potvf9uil.png
---

Hey, if you don't know what I'm talking about, you should read [my first article through this link](https://dev.to/ftonato/creating-a-microblog-using-vue-supabase-31p).

**Context:**

We've created a microblog using _Vue_ + _Supabase_ (an open-source Firebase alternative). Today we're going to show a new publication whenever it is inserted into the database.

---

Our starting point will be the code created in the last article, you can access the [repository to view the source code](https://github.com/ftonato/vue-supabase-microblog).

Our main _branch_ of git, is called `main`, we will create a branch from this called `feat/add-subscription` ([you can access it here](https://github.com/ftonato/vue-supabase-microblog/tree/feat/add-subscription)), we can do this using the following command on the command line:

```js
// git clone git@github.com:ftonato/vue-supabase-microblog.git
// cd vue-supabase-microblog

git checkout -b feat/add-subscription
```

By browsing the [documentation](https://supabase.io/docs/client/subscribe), we can find out how to subscribe in detail.

A subscription is like to watch changes in realtime in your database. This means that each time an event (`INSERT`, `UPDATE`, `DELETE`, `*`) happens, we can trigger a function.

E.g.:

```js
const mySubscription = supabase
  .from('*')
  .on('*', payload => {
    console.log('Change received!', payload)
  })
  .subscribe()
```

In the example above we are saying to our application: "Whenever an event happens, whatever the table, print the _payload_ information using a `console.log`.


What we will do is similar to the example, with two different details:

1. We will only watch from one table (`posts`).
2. We only want to watch at the `INSERT` event.

----

In our [List.vue](https://github.com/ftonato/vue-supabase-microblog/blob/main/src/components/List.vue) file, we will create a new variable called `subscriptionPosts` and a method `subscribePosts`.

We will call this method when assembling (`mounted`) our component and its responsibility should be:

- Whenever a new record is inserted in this table, add it to the `posts` variables (local variable that stores the publications).

Below our code with the implementation:

```vue
<template>
  <section class="px-2 pt-16 pb-6 bg-white md:px-0">
    <div class="container items-center max-w-6xl px-8 mx-auto xl:px-5">
      <template v-for="(post, index) in posts">
        <list-item
          :key="`post-${index}`"
          :id="post.id"
          :title="post.title"
          :description="post.description"
        />
      </template>
    </div>
  </section>
</template>

<script>
import ListItem from "./ListItem";
import DatabaseService from "../Database.service";

export default {
  name: "List",
  components: {
    ListItem,
  },
  data: () => ({
    posts: [],
    database: null,
    subscriptionPosts: undefined,
  }),
  created() {
    const database = new DatabaseService();
    this.database = database.getInstance();
  },
  async mounted() {
    await this.fetchPosts();
    this.subscribePosts();
  },
  methods: {
    async fetchPosts() {
      let { error, data } = await this.database
        .from("posts")
        .select()
        .order("id");
      if (error) {
        console.error(error);
        return;
      }

      this.setPosts(data);
    },
    setPosts(posts) {
      this.posts = posts;
    },
    subscribePosts() {
      this.subscriptionPosts = this.database
        .from("posts")
        .on("INSERT", (message) => {
          if (message.new) {
            this.posts.push(message.new);
          }
        })
        .subscribe();
    },
  },
};
</script>
```

This is the code required for realtime subscription to be implemented.

Are you ready to see the result?

![Realtime Subscription](https://dev-to-uploads.s3.amazonaws.com/i/62xcoy51vorlfomoaqg4.gif)

**Definitely spectacular!**

---

What was done above would be enough, but let's take a little care of our application and remove the subscription in the dismantling (`destroyed`) of our component.

> Always unsubscribe, when new values in the subscribed stream is no more required or don't matter, it will result in way less number of triggers and increase in performance in a few cases.

We create a method called `unsubscribePosts` which will be responsible for removing the subscription.

```vue
<template>
  <section class="px-2 pt-16 pb-6 bg-white md:px-0">
    <div class="container items-center max-w-6xl px-8 mx-auto xl:px-5">
      <template v-for="(post, index) in posts">
        <list-item
          :key="`post-${index}`"
          :id="post.id"
          :title="post.title"
          :description="post.description"
        />
      </template>
    </div>
  </section>
</template>

<script>
import ListItem from "./ListItem";
import DatabaseService from "../Database.service";

export default {
  name: "List",
  components: {
    ListItem,
  },
  data: () => ({
    posts: [],
    database: null,
    subscriptionPosts: undefined,
  }),
  created() {
    const database = new DatabaseService();
    this.database = database.getInstance();
  },
  async mounted() {
    await this.fetchPosts();
    this.subscribePosts();
  },
  destroyed() {
    this.unsubscribePosts();
  },
  methods: {
    async fetchPosts() {
      let { error, data } = await this.database
        .from("posts")
        .select()
        .order("id");
      if (error) {
        console.error(error);
        return;
      }

      this.setPosts(data);
    },
    setPosts(posts) {
      this.posts = posts;
    },
    subscribePosts() {
      this.subscriptionPosts = this.database
        .from("posts")
        .on("INSERT", (message) => {
          if (message.new) {
            this.posts.push(message.new);
          }
        })
        .subscribe();
    },
    unsubscribePosts() {
      this.database.removeSubscription(this.subscriptionPosts);
    },
  },
};
</script>
```

----

**That's all Folks!**

Think of the power that this brings to an application and as I said in the last publication: _Let your imagination guide you and explore new horizons._

If you are interested in the source code of the project we created, go to the project directory on GitHub and implement even more exciting things, such as:


If you have any question, do not hesitate to contact me (ademilsonft@outlook.com / [@ftonato](https://twitter.com/ftonato) or the [Supabase team](https://supabase.io/docs/support)).