Lukas
Lukas

Reputation: 603

How to create an Array inside firestore?

Which code do I need to create an Array in Firebase Firestore?

I want to store userDetails:

  userName: this.userProfile.name,
  userImage: this.userProfile.image,
  userId: this.userProfile.userId

as an Array inside Firestore

Vue component:

...
data () {
 return {
     postDetails: {
      createdOn: new Date(),
      content: '',
      userId: null,
      image: null,
      comments: 0,
      likes: 0,
      userDetails: []
    }
    userData: [
     { userName: this.userProfile.name },
     { userImage: this.userProfile.image},
     { userId: this.userProfile.userId }
 }
},
methods: {
  createPost () {
    fb.postsCollection.add({
      createdOn: this.postDetails.createdOn,
      content: this.postDetails.content,
      userId: this.currentUser.uid,
      image: this.postDetails.image,
      comments: this.postDetails.comments,
      likes: this.postDetails.likes
      userData: this.userData
    }).then(ref => {
      this.post.content = ''
      this.$router.push('/dashboard')
    }).catch(err => {
      console.log(err)
    })
  }
}

End result should look likes this one

Upvotes: 1

Views: 2471

Answers (1)

Renaud Tarnec
Renaud Tarnec

Reputation: 83093

I see that you are adapting the code from this Firestore and Vue.js tutorial: https://savvyapps.com/blog/definitive-guide-building-web-app-vuejs-firebase.

Actually in this tutorial the userProfile data is coming from the vue-store with

  computed: {
    ...mapState(['userProfile', 'currentUser', 'posts'])
  },

This part of the code is missing in your question but it is most probably the cause of your problem: In your Vue.js component, you try to use computed properties in data but this is not possible "because of component creation timing: data evaluates before computed properties".

See Use computed property in data in Vuejs and https://forum.vuejs.org/t/computed-properties-in-data/11231

Just access directly the computed properties as follows, and it will work: userData will be stored as an array.

methods: {
  createPost () {
    fb.postsCollection.add({
      createdOn: this.postDetails.createdOn,
      content: this.postDetails.content,
      userId: this.currentUser.uid,
      image: this.postDetails.image,
      comments: this.postDetails.comments,
      likes: this.postDetails.likes
      userData: [
        { userName: this.userProfile.name },
        { userImage: this.userProfile.image},
        { userId: this.userProfile.userId }
      ]
    }).then(ref => {
      this.post.content = ''
      this.$router.push('/dashboard')
    }).catch(err => {
      console.log(err)
    })
  }
}

Upvotes: 1

Related Questions