简体   繁体   中英

typeahead.js does not get data from local

First of all, it's a newbie question:) Sorry for bothering you...

I've managed to get data from Firebase Firestore, and put that data in a variable.

var db = firebase.firestore();
  let contentJSON = [];
db.collection("blog-posts").get().then(function(querySnapshot) {
    querySnapshot.forEach(function(doc) {
var listTemp = {
    "category": doc.data().category,
    "content": doc.data().content,
    "date": doc.data().date,
    "slug": doc.data().slug,
    "title": doc.data().title
  };
contentJSON.push(listTemp)
    });
});

Then I create the new Bloodhund instance with this local data.

var blogPosts = new Bloodhound({
  datumTokenizer: Bloodhound.tokenizers.obj.whitespace('content'),
  queryTokenizer: Bloodhound.tokenizers.whitespace,
  local: contentJSON,
  });

Nothing appears when I search through this setup. I've tried to run it with external JSON with the Prefetch method and it worked, however, I need to run it with local data. I think there is a problem with the structure of the local data variable. Could you please take a look and help me?

This is probably an AJAX problem that could be solved with promises and async/await.

The first body of code must resolve .then() you may run the second body of code. Otherwise the firebase code completes after the bloodhound, and it must complete before.

If you put the firebase code into a function like this

// (1) add async here
async getBlogPosts() {
  var db = firebase.firestore();
  // (2) add return here
  return db.collection("blog-posts").get().then(function(querySnapshot) {
    querySnapshot.forEach(function(doc) {
    // (3) move variable in here
    let contentJSON = [];
    var listTemp = {
    "category": doc.data().category,
    "content": doc.data().content,
    "date": doc.data().date,
    "slug": doc.data().slug,
    "title": doc.data().title
    };
    contentJSON.push(listTemp)
    // (4) return here
    return contentJSON
    });
});

And then call it with an await in your front end code

// (5) the async await will make sure this function happens before we proceed
var contentJSON = await getBlogPosts()
var blogPosts = new Bloodhound({
  datumTokenizer: Bloodhound.tokenizers.obj.whitespace('content'),
  queryTokenizer: Bloodhound.tokenizers.whitespace,
  local: contentJSON,
  });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM