niclas_4
niclas_4

Reputation: 3674

Fetched store property returns undefined on page computed

So I have a Store that gets filled with a post data which is then displayed on the page, but for some reason, the post variables are not defined. Here is some code:

Async Fetch in the component

async fetch({ store, route }) {
    db.collection("posts")
      .doc(route.params.id)
      .get()
      .then(doc => {
        if (doc.exists) {
          var x = doc.data()
          x.docID = doc.id
          store.commit("modules/posts/pushPost", x)
        } else alert("No Post found")
      })
},

Computed Property in the Component

 computed: {
    post() {
      var posts = this.$store.state.modules.posts.posts
      return posts.find(x => x.docID === this.$route.params.id)
    },

Store Commit

pushPost(state, post) {
    state.posts.push(post)
    console.log(post)
    console.log("pushed")
  }

Both consoles log in the store trigger and display the correct values But for some reason the computed post in my page is undefined

Upvotes: 1

Views: 60

Answers (2)

Eyk Rehbein
Eyk Rehbein

Reputation: 3868

I would completely forget about the .then callback in this particular case. If you code it like in the following example, you will definitely have no problem with undefined data and it's much cleaner code.

async fetch({ store, route }){
    const doc = await db.collection("posts").doc(route.params.id).get()

    if(doc.exists) {
      const x = doc.data()
      x.docID = doc.id
      store.commit("modules/posts/pushPost", x)
    } else {
      alert("No Post found")
    }
}

Upvotes: 1

niclas_4
niclas_4

Reputation: 3674

I found the source of the problem.

The await keyword before the db call to fetch the data was missing which leaded to the component being ready too fast before the store was actually filled, that obviously caused the data to be undefined.

Upvotes: 0

Related Questions