JS_is_awesome18
JS_is_awesome18

Reputation: 1757

Refreshing vue.js app without hard reloading

I am building a Vue.js todo list CRUD app based on a tutorial posted on Medium: (part 1) https://medium.com/@magyarn/vuefire-crud-todo-list-app-part-1-e069c46b50c6, (part 2) https://medium.com/@magyarn/vuefire-crud-todo-list-app-part-2-8bd61ae0d066

I built the app in it's entirety and was successful in connecting it to a Firestore database. However, there doesn't seem to be a way to render the list items on the DOM once they have been added to the database. In other words, I have to click the browser refresh button to see the list items on the screen after they have been added to the database. To resolve this, I added window.location.reload to each method to automatically trigger a page reload whenever I click add, edit, or delete, but this doesn't seem like a good long-term solution. Here is an example:

    addTodo() {
      todosCollection.add({
        text: this.newTodo,
        completed: false,
        id: this.todos.length,
        createdAt: new Date()
      })
      .then(() => {
        window.location.reload()
      })
   deleteTodo(todo) {
      todosCollection.doc(todo.id).delete()
      .then(() => {
        window.location.reload()
      })
    },

I also added a special hook in order to retrieve the items in the database and render them to the DOM after manually refreshing:

methods: {
...
},
created(){
    todosCollection.get()
    .then(snapshot => {
      snapshot.forEach(doc => {
        let newTodo = doc.data()
        newTodo.id = doc.id
        this.todos.push(newTodo)
      })
    })
  }

My question is what is the best way to handle refreshing without reloading for this kind of single page Vue.js app? Thanks!

Upvotes: 1

Views: 2664

Answers (1)

ittus
ittus

Reputation: 22403

There are few ways to do it:

Method 1: Using Vuefire binding

Remove your getting list in created and add following code to your component:

  firestore() {
    return {
      todos: todosCollection.orderBy('createdAt', 'desc')
    }
  },

Vuefire document

Method 2: Update your list manually. First, separate getting data to a method and call it in created hook and after each actions

created() {
  this.getData()  
},
methods: {
  getData() {
    const todos = []
    todosCollection.get()
    .then(snapshot => {
      snapshot.forEach(doc => {
        let newTodo = doc.data()
        newTodo.id = doc.id
        todos.push(newTodo)
      })
      this.todos = todos
    })
  },
  addTodo() {
      todosCollection.add({
        text: this.newTodo,
        completed: false,
        id: this.todos.length,
        createdAt: new Date()
      })
      .then(() => {
        this.getData()
      })
  },
  deleteTodo(todo) {
    todosCollection.doc(todo.id).delete()
    .then(() => {
      this.getData()
    })
  },
}

Upvotes: 3

Related Questions