Created
May 9, 2018 19:10
-
-
Save sejr/443282f8a5a67ccffe9ced89416f182b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<template> | |
<div class="section posts"> | |
<p v-for="(post, index) in posts" :key="post.id"> | |
{{ `${index}: ${post.data.body}` }} | |
</p> | |
</div> | |
</template> | |
<script> | |
import fb from '../fb' | |
const db = fb.firestore() | |
export default { | |
name: 'Posts', | |
data () { | |
return { | |
posts: [] | |
} | |
}, | |
computed: { | |
user () { | |
return fb.auth().currentUser | |
} | |
}, | |
created () { | |
// Fetch posts from cache | |
this.posts = JSON.parse(localStorage.getItem('posts')) || {} | |
// See Firebase documentation on building queries for array-like structures: | |
// https://firebase.google.com/docs/firestore/solutions/arrays | |
db.collection('posts').where(`recipients.${this.user.uid}`, '>', 0) | |
.orderBy(`recipients.${this.user.uid}`).limit(10) | |
.onSnapshot(posts => { | |
posts.docChanges.forEach(change => { | |
if (change.type === 'added') return this.addOrUpdatePost(change) | |
if (change.type === 'modified') return this.addOrUpdatePost(change) | |
if (change.type === 'removed') return this.removePost(change) | |
}) | |
}) | |
}, | |
methods: { | |
addOrUpdatePost (postEvent) { | |
let post = { | |
id: postEvent.doc.id, | |
data: postEvent.doc.data() | |
} | |
this.$set(this.posts, postEvent.newIndex, post) | |
window.localStorage.setItem('posts', JSON.stringify(this.posts)) | |
}, | |
removePost (postEvent) { | |
// Reactive objects get special treatment: | |
// https://vuejs.org/v2/guide/reactivity.html | |
console.log(postEvent.oldIndex) | |
this.posts.splice(postEvent.oldIndex, 1) | |
window.localStorage.setItem('posts', JSON.stringify(this.posts)) | |
} | |
} | |
} | |
</script> | |
<style lang="scss" scoped> | |
</style> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment