N
N
Nikita Kotenko2018-05-06 15:27:37
firebase
Nikita Kotenko, 2018-05-06 15:27:37

How to create a property in data based on data from firestore?

The component's data has an input_value property that is associated with the input. When loading the page, it was assumed that the value of the input was substituted with the value from the store. But input_value after page load is always = undefined. Tried to force assign in created() and mounted() hooks: this.input_value = this.user.custombutton

<template>
  <div>
    <span>{{user.custombutton}}</span> <!-- здесь  данные в store уже существуют-->
    <input v-model="input_value"> 
  </div>
</template>

export default {
  name: 'CustomButton',
  data: function () {
    return {
      input_value: this.user.custombutton // а здесь данных в store как будто еще не существует, input_value undefined
    }
  },
  computed: {
    user() {
      return this.$store.state.user
    }
  }
}


index.js (in store/ directory)
export default new Vuex.Store({
  state: {
    user: {}
  },
  mutations: {
    init(state, payload) {
      state.user = payload;
    }
  }
});


main.js (in src)
firebase.auth().onAuthStateChanged(function(user) {
  if (user) {
    var userID = user.uid
    db.collection("users").doc(userID)
    .onSnapshot(function(doc) {
      userdata = doc.data()
      store.commit('init', userdata)
    });
  }

  new Vue({
    el: '#app',
    router,
    store,
    components: { App },
    template: '<App/>',
    render: h => h(App),
    mounted () {
      // You'll need this for renderAfterDocumentEvent.
      document.dispatchEvent(new Event('render-event'))
    }
  })
});


From the template, the data in the store is visible and rendered in time. It seems that the data from the database arrive somehow at the wrong time. But after making changes to the file and saving the application, it is recompiled on the fly and already existing data arrives in the browser without reloading the page and the input is filled with data from the store. I already thought about making requests to the database directly from the component, but I have about 10 such component inputs, and 10 requests when loading the page - the solution is not very good, although it is working.

What am I doing wrong?

By the way, I'm not the only one experiencing this.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2018-05-06
@n_angelo

Try tracking user changes, i.e.:

export default {
  name: 'CustomButton',
  data: () => ({
    input_value: '',
  }),
  computed: {
    user() {
      return this.$store.state.user;
    },
  },
  watch: {
    user(val) {
      this.input_value = val.custombutton;
    },
  },
};

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question