little problem for a beginner

31 views
Skip to first unread message

bussiere adrien

unread,
Aug 21, 2016, 8:16:23 PM8/21/16
to PouchDB
i 've made a little snippet but i do'nt understand where i'am wrong  :

<html>
<script src="https://cdn.jsdelivr.net/pouchdb/5.4.5/pouchdb.min.js"></script>
<script>
var db = new PouchDB('my_database');
function addTodo(text) {
var todo = {
_id: new Date().toISOString(),
title: text,
completed: false
};
db.put(todo, function callback(err, result) {
if (!err) {
console.log('Successfully posted a todo!');
}
});
}
addTodo("test2");
function showTodos() {
db.allDocs({include_docs: true, descending: true}, function(err, doc) {
var data = "";
for (var key in doc.rows )
{
data += doc.rows[key].title+"<br/>";
}
document.getElementById('comments').innerHTML= data;
});
}
showTodos() ;
</script>
<body>
<div id="comments">

</div>
</body>
</html>


this code show me always undefined instead of the title.

if anyone have any idea

regards and thanks

Dale Harvey

unread,
Aug 22, 2016, 4:31:26 AM8/22/16
to pou...@googlegroups.com
There are 2 issues in your code snippet, the first is that `doc.rows[key].title` is undefined, in pouchdb the way that is returned from allDocs is in the format `doc.rows[key].doc.title`, to be honest I would prefer your way however this was done for CouchDB compatibility.

The second issue is that you are calling

addTodo("test2");
showTodos();

There is no guarantee that addTodo will have finished its async operations before showTodos is called, you can fix this by adding a return to addTodo and waiting on the returned promise

  addTodo("test2").then(function() {
    showTodos();
  });


This post may help you understand the promise issue (https://pouchdb.com/2015/05/18/we-have-a-problem-with-promises.html), and there is a working example of the changes @ http://paste.pouchdb.com/paste/74f8n2/

Cheers
Dale

--
You received this message because you are subscribed to the Google Groups "PouchDB" group.
To unsubscribe from this group and stop receiving emails from it, send an email to pouchdb+unsubscribe@googlegroups.com.
To post to this group, send email to pou...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/pouchdb/1e0a09ed-ba26-439e-b3d2-7f840e06a462%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply all
Reply to author
Forward
0 new messages