-
Notifications
You must be signed in to change notification settings - Fork 6
/
index.js
102 lines (89 loc) · 2.53 KB
/
index.js
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
import Vue from 'vue'
import Vuex from 'vuex'
const fb = require('./../firebaseConfig.js')
Vue.use(Vuex)
// realtime updates from our notes collection
fb.notesCollection.orderBy('createdOn', 'desc').onSnapshot(querySnapshot => {
let notesArray = []
querySnapshot.forEach(doc => {
let note = doc.data()
note.id = doc.id
notesArray.push(note)
})
store.commit('loadNotes', notesArray)
})
export const store = new Vuex.Store({
state: {
notesList: [],
note: {},
performingDelete: false,
performingAdd: false,
performingUpdate: false
},
actions: {
async deleteNote ({ commit, state }) {
let id = (state.note && state.note.id)
if (id) {
try {
commit('setPerformingDelete', true)
await fb.notesCollection.doc(id).delete()
commit('setPerformingDelete', !state.performingDelete)
} catch (error) {
console.error(error)
}
}
commit('setNote', {})
},
setNote ({ commit }, { id = '', body = '' } = {}) {
commit('setNote', { id, body })
},
async saveNote ({ commit, state }) {
const { id, body, title } = state.note
if (id) { // update
commit('setPerformingUpdate', true)
await fb.notesCollection.doc(id).update({
body,
title,
updatedOn: fb.firebase.firestore.Timestamp.now()
})
commit('setPerformingUpdate', !state.performingUpdate)
} else { // add
commit('setPerformingAdd', true)
await fb.notesCollection.add({
body,
title,
createdOn: fb.firebase.firestore.Timestamp.now(),
updatedOn: fb.firebase.firestore.Timestamp.now()
})
commit('setPerformingAdd', !state.performingAdd)
}
commit('setNote', {})
}
},
mutations: {
loadNotes (state, notes) {
state.notesList = notes
},
setNote (state, note) {
let localNote = {}
const { id, body } = note
if (id) {
localNote = state.notesList.find(n => n.id === id)
const newNoteBody = body || localNote.body
localNote = { ...note, body: newNoteBody, title: newNoteBody.substring(0, 20) }
} else if (body) {
localNote = { body, title: body.substring(0, 20) }
}
state.note = localNote
},
setPerformingDelete (state, flag) {
state.performingDelete = flag
},
setPerformingAdd (state, flag) {
state.performingAdd = flag
},
setPerformingUpdate (state, flag) {
state.performingUpdate = flag
}
}
})