Search code examples
javascriptfirebasevue.jsgoogle-cloud-firestorevuefire

How do i display data from db on a route change?


I'm working on a messenger-like app in vue.js + firebase. What im'trying to do is to - on every route change get some of the data coresponding to the id(stored in route) from db and then display it on the screen. I am getting some weird behaviour with this data and it doesn't work how intended.

The code:

  methods: {
    getRoomName() {
      db.collection("rooms")
        .doc(this.params)
        .onSnapshot((snapshot) => (this.roomName = snapshot.data().name));
    },
  },
  watch: {
    $route(to, from) {
      this.getRoomName();
    },
  },

where data:

data() {
    return {
      input: "",
      roomName: "",
      params: this.$route.params.id,
      message: "",
      roomNameTest: "",
    };
  },

template: <span class="roomName">{{roomName}}</span>


Solution

  • First thing I noticed is that you are calling this.$route at data(), it will not work. If you need to populate something, try using Vue Lifecycle Hooks.