Vue3 - updated array not rendered automatically

Quite new to Vue, I cannot figure out how to automatically render my updated array.

I have a very basic page including an input, and a button. When the button is clicked, the data is saved in a MongoDB via my server.

Right below the form, I'm displaying the fetched data from Mongo.

But, when I create a new item, I need to reload the page to see the updated list. How should I proceed to see the table updating "live"?

Here is my Vue Code:

<template>
  <div class="home">
    <h1>Hello</h1>
    <form submit.prevent="">
      <input v-model="newItem" type="text">
    </form>
    <button @click="createItem">Create</button>
    <div>
      <table>
        <tr>
          <th>Name</th>
        </tr>
        <tr v-for="(item, index) of items" :key="index">
          <td>{{ item.name }}</td>
        </tr>
      </table>
    </div>
  </div>
</template>

<script>
import CrudService from '../services/crud.service';
import { ref } from 'vue';

export default {
  data(){
    return{
      newItem: '',
      items: [],
    }
  },

  async mounted(){
    await this.readItems();
  },

  methods: {
    async readItems(){
      const results = await CrudService.readItems();
      results.data.forEach(element => {
        ref(this.items.push(element));
      });
    },

    async createItem(){
      await CrudService.createItem({ item: this.newItem });
    }
  }
}
</script>

Solution 1:

You could call the readitems() method after created item to update your view without refreshing.

<script>
import CrudService from '../services/crud.service';
import { ref } from 'vue';

export default {
  data(){
    return{
      newItem: '',
      items: [],
    }
  },

  async mounted(){
    await this.readItems();
  },

  methods: {
    async readItems(){
      const results = await CrudService.readItems();
      this.items = [];//add this line to clear items firstly
      results.data.forEach(element => {
        ref(this.items.push(element));
      });
    },

    async createItem(){
      await CrudService.createItem({ item: this.newItem });
      await this.readItems();//add this line
    }
  }
}
</script>