aboutsummaryrefslogtreecommitdiff
path: root/app/components/post_form.js
blob: 1f45f0c53f4b222cfb3427e4a89c0db7f5c36f27 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import Axios from 'axios';
import Vue from 'vue';
import AuthService from '../services/auth';

const internals = {};

internals.kPostsRoute = '/api/posts';

export default internals.PostFormComponent = Vue.component('post-form', {
  template: '<div class="post-form-container">' +
      '<h1>hi {{authService.user.name}}</h1>' +
      '<button v-show="!active" class="post-submit" v-on:click="activate">Post something.</button>' +
      '<textarea v-show="active" :disabled="submitting" v-model="content" class="post-content-input" placeholder="tell us something" maxlength=255></textarea>' +
      '<p v-show="message" class="post-form-error">{{message}}</p>' +
      '<button v-show="active" :disabled="submitting" class="post-submit" v-on:click="submit">Go.</button>' +
      '</div>',

  data() {

    return {
      content: '',
      message: '',
      submitting: false,
      active: false,
      authService: new AuthService()
    };
  },

  methods: {

    // Activates the form.

    activate() {

      this.active = true;
    },

    // Creates a post

    submit() {

      this.submitting = true;

      return Axios({
        method: 'post',
        headers: {
          Authorization: `Bearer ${this.authService.token}`
        },
        data: {
          content: this.content
        },
        url: internals.kPostsRoute
      }).then((response) => {

        this.$emit('post-submitted', response.data);
        this.content = '';
        this.message = '';
        this.submitting = false;
        this.active = false;
      }).catch((err) => {

        console.error(err.stack);
        this.submitting = false;
        this.message = 'Error while creating the post...';
      });
    }
  }
});