21. Show notifications

In the previous article, we were marking the notifications as read. But we were not displaying the notifications. In this article, we are going to show notifications in a bootstrap table. Since we are already getting the notifications in the global $user object, we need to create a Vuex store because later in this tutorial series, we will be using sockets to automatically prepend the notification without having to refresh the page.

So open vuex/store.js and initialize an array.

notifications: [],

Then we need to create its mutators to set the value anywhere from the app.

mutations: {
    setNotifications (state, notifications) {
        state.notifications = notifications
    },
    ...
}

Also, we need to create a getter that will help us get the value.

getters: {
    getNotifications (state) {
        return state.notifications
    },
    ...
}

Then we need to set this notifications array in the “/getUser” API response when the status is a success. Same as we did for unreadNotifications the variable. So open your AppHeader.vue and write the following line when the /getUser API response status is success:

store.commit("setNotifications", response.data.user.notifications)

And in NotificationsComponent.vue, we need to create its computed property first.

// create computed property for all notifications
computed: {
    notifications() {
        return store.getters.getNotifications.reverse()
    }
}

This will save the notifications in an array. But to show the notifications, we need to write HTML and render the Javascript array in it. Then after the heading row, create another <div> row to create a table.

<div class="row">
    <div class="col-md-12">
        <!-- show all notifications -->
        <table class="table table-hover">
            <thead>
                <tr>
                    <th>Type</th>
                    <th>Actions</th>
                </tr>
            </thead>

            <tbody>
                <tr v-for="notification in notifications" v-bind:key="notification._id">
                    <!-- show type of notification -->
                    <td>
                        <span v-text="notification.type"></span>&nbsp;

                        <!-- if type is group invite, then we also show the name of group -->
                        <template v-if="notification.type == 'group_invite'">
                            <span v-text="notification.group.name"></span>
                        </template>
                    </td>
                </tr>
            </tbody>
        </table>
    </div>
</div>

If you check the notifications page now, you will be able to see all your notifications.

show notifications
show notifications

Now we need to have the ability to delete the notifications.





Please disable your adblocker or whitelist this site!