Build a Twitter Clone With Adonis and Vue

Tweeting

Now let's allow users to post tweets. We already created the component that contains a text box for posting tweets. All we have to do now is add the implementation for posting tweets.

Firstly, let's update the form tag in UserSidebar as below:

// src/components/User/UserSidebar.vue

<form class="ui form" @submit.prevent="postTweet">

Once the form is submitted, a postTweet method will be called. Now, let's create the postTweet method. Still inside UserSidebar.vue, add the code below to the JavaScript section:

// src/components/User/UserSidebar.vue

// add this after `<script>`
import EventBus from '@/eventBus'

methods: {
    postTweet () {
        const token = localStorage.getItem('tweetr-token')

        axios
            .post(
                '/tweet',
                { tweet: this.tweet },
                {
                    headers: {
                        Authorization: `Bearer ${token}`
                    }
                }
            )
            .then(response => {
                // fire an event to the event bus
                EventBus.$emit('tweetAdded', response.data.data)

                // clear input field
                this.tweet = ''
            })
    }
}

This makes a POST request to the /tweet endpoint of our API to pass along the user's token. Once the tweet is posted successfully, we will add the newly created tweet to the list of tweets on the Tweets component. But the UserSidebar and Tweets components are not really parent and child. Therefore, they can't easily communicate by pasing props. So, we have to use something called EventBus. When the tweet is posted, we fire an tweetAdded event to the event bus passing along the tweet that was posted. Then we clear the input field. For this to work, notice we import the EventBus which we'll create shortly.

Creating The Event Bus

Create a eventBus.js file directly in the src folder and add the code below in it:

// src/eventBus.js

import Vue from 'vue'

export default new Vue()

This is just a bare bone Vue instance.

Listening For tweetAdded Event

We have fired the tweetAdded event but it will be useless if we don't listen for this event and update the Tweets component accordingly. So, open src/components/Tweet/Tweets.vue and add the code below to the JavaScript section:

// src/components/Tweet/Tweets.vue

// add this after `<script>`
import EventBus from '@/eventBus'

created () {
    // listen for event fired
    EventBus.$on('tweetAdded', this.fetchAddedTweet)
},
methods: {
    fetchAddedTweet (tweet) {
        // add tweet to top of tweets
        this.tweets.unshift(tweet)
    }
}

On creation of the component, we listen for the tweetAdded event fired then call a fetchAddedTweet method. This means, once the event is fired, the fetchAddedTweet method will be called. The fetchAddedTweet method simply add the new tweet to the top of existing tweets.

We can now start posting tweets: