Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Computed / async data fetching

I'm trying to create simple Vue + CouchDB apps. With Vanilla JS this works fine but I don't get the data fetched from the database with a promise or async function to my vue instance. Here is my code:

app.html

<div id="vue-app">
  <table>
    <thead>
      <tr>
        <th>{{ tableHead.name }}</th>
        <th>{{ tableHead.lastname }}</th>
      </tr>
    </thead>
    <tbody>
      <tr v-for="data in tableData">
        <td>{{ data.name }}</td>
        <td>{{ data.lastname }}</td>
      </tr>
    </tbody>
  </table>
</div>

app.js

const db = new PouchDB('testdb')

const couch = {
  fetchData: async function () {
    var dbData = await db.allDocs({
        include_docs: true,
        descending: true
    }).then(function (result) {
        var objects = {}
        result.rows.forEach(function (data) {
            objects[data.id] = data.doc
        })
        return objects
    }).catch(function(err) {        
        return err
    })
    return dbData
  }
}

var app = new Vue({
    el: '#vue-app',
    data: {
        tableHead: {
            name: 'Name',
            lastname: 'Lastname'
        }
    },
    computed: {
        async tableData () {
            var dbData = await fetchData()
            return dbData
        }
    }
})

Hope you can teach me the right way to fetch my data to my Vue instance!

like image 398
pazzero Avatar asked Feb 17 '26 22:02

pazzero


1 Answers

Welcome to SO!

Computed properties are not meant to be async.

The usual pattern to address async retrieval of data is to:

  1. Use an internal data placeholder
  2. Initiate the async request on component lifecycle hook created or mounted
  3. On request success, update the internal data with the new content.
  4. Use the internal data in your template.

In your case, you would:

  1. Turn your tableData into an internal data, like your tableHead
  2. Call your couch.fetchData function in created hook.
  3. In the function returned Promise then chain (or after awaiting), assign your tableData with the result
  4. Use tableData in your template (nothing to change)

See for example the Vue cookbook to consume APIs with Axios

like image 99
ghybs Avatar answered Feb 20 '26 10:02

ghybs