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

105 Views Asked by At

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>

3

There are 3 best solutions below

0
On BEST ANSWER

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.

0
On

I am using the $route.path to watch for changes to get the new IDs.

Component

  computed: {
    ...mapState('products', ['products']),
  },
  watch: {
    '$route.path'() {
      this.bindProducts(this.IdFromUrl)
    },
  },

  mounted() {
    this.bindProducts(this.IdFromUrl)
  },

  methods: {
    ...mapActions('products', ['bindProducts']),
  }

And the running in my store there is vuexfire working. Alternatively you could bind your own data.

4
On

The life cycle hooks (mounted/created are for these kinds of things. They are called when the vue instance is created and mounted respectively.

mounted() // it can also work for the created hook {
  this.getRoomName();
},

The watcher watches for route change but is not really suited for this situation because by the time the route changes, the component in which it's watching has not been instantiated. The mounted/created hooks are triggered when that particular Vue instance you are watching in is instantiated/mounted respectively.

An appropriate time to use a watcher for a route change is if the params on a url changes and you need to do something. An example is changing /users/1 to /users/2`. This will work because the same component is used and the watcher will detect the change.