Using typeahead.js to return list of Facebook friends - facebook

I am using the Facebook Graph API to return a list of Facebook friends. I then want to run the returned JSON into Typeahead.js as follows:
$(document).ready(function () {
$('input.friends').typeahead({
name: 'friends',
prefetch: 'https://graph.facebook.com/me/friends?access_token=<?php echo $access_token;?>',
ttl: 0,
template: [
'<p class="name-tag">{{name}}</p>'
].join(''),
engine: Hogan
});
});
My corresponding HTML is as follows:
<input class="friends typeahead" type="text" placeholder="Start typing" id="friends">
But nothing is being returned using the prefetch (with hardcoded, local values, no problem). I am not seeing any errors in the console regarding cross-domain issues.
I am fairly sure this is because Typeahead hasn't been told how to handle the JSON structure, but I am unsure how to achieve this. I have tried implementing the templating system Hogan (which I will admit to being unfamiliar with) but this has not helped.
Any ideas much appreciated.
Many thanks

You need to either use valueKey if the result is a simple list of objects, from which you want to use a specific key as your values, or alternatively use a filter: to convert the result into a flat list of suggestions.
In your case, the response is a object with a data member that is a list of name, id pairs. You can have filter() be a function that returns response.data (to extract the list from the data member), and then set valueKey to name.

Thanks Nitzan.
My code snippet currently looks like:
valueKey: 'name',
remote: {
url: 'https://graph.facebook.com/me/friends?access_token=<?php echo $access_token;?>',
filter: function (response) {
return response.data;
},
},
template: [
'<p>{{name}}</p>',
].join(''),
engine: Hogan
Which returns ALL the names in the JSON at once, no matter what is in the input box.
Is this a problem with the filter or something else?

Solution below. Remember to include Hogan if you're using that as your templating engine, as I have done:
$.get('https://graph.facebook.com/me/friends?access_token=<?php echo $access_token;?>', function(server_data){
var rt = {};
for (var i in server_data.data)
rt[server_data.data[i].id] = {name:server_data.data[i].name, id:server_data.data[i].id},
//rt.push({name:server_data.data[i].name})
console.log(rt)
$('input.friends').typeahead({
limit: 10,
name: 'friends',
valueKey: 'name',
local:rt,
template: [
'{{id}}',
].join(''),
engine: Hogan
});
})

Related

RTK Query url with parameter which is an array

I am currently trying to pass in an array to a query which will be used as parameters but keeping encountering an issue that the object doesn't seem to take an array in the parameters and doesn't format the url param string as I need.
Here is my array that is passed into my RTK hook:
filterArguments = [1,2]
RTK Query:
getFood: builder.query({
// The URL for the request is '/fakeApi/posts'
query: (filterArguments) => ({
url:'/user/food/',
params: {
...filterArguments
}
}),
providesTags:['Food']
}),
This is bringing back an error or if i fiddle around with it an send an object through it brings back the following URL ignoring other items in the object of the same name:
test:8000/api/?filter=1
However this is not the desired result, the desire url result from passing an array of filter id's would be:
test:8000/api/?filter[]=1&filter[]=2
is this achievable in RTK query? and how would i achieve this?
redux-toolkit doesnt implement any special http library. It uses fetch under the hood. For params, it uses URLSearchParams(). So the API will be similar. Since URLSearchParams() doesnt support your params notation, you can use the query-string library:
const queryString = require('query-string');
getFood: builder.query({
query: (filterArguments) => ({
url:'/user/food/' + queryString.stringify({filter: filterArguments}, {arrayFormat: 'bracket'}),
}),
providesTags:['Food']
}),

Using v-switch in vuejs and firebase object in a component, how to show the value from firebase in the v-switch

I need v-switch starts with the value from firestore object, here ( {{usuario.tabVisibleCatalogo}} ) i got the rigth value from firestore:
<template>
<v-btn #click="estadoPublico" flat>
{{usuario.tabVisibleCatalogo}}
buet here, i donĀ“t get the value from firestore when the component start or re render, it shows the value from data:
<v-switch v-model="switch1" :label="`Publicado: ${switch1.toString()}`"></v-switch>
</v-btn>
</template>
<script>
export default {
data: () => ({
switch1: false,
}),
computed: {
...mapState('sesion', ['usuario']),
},
methods: {
async estadoPublico () {
try {
await db.collection('usuarios')
.doc(this.usuario.uid)
.update({
tabVisibleCatalogo: this.switch1,
})
}...
},
}
</script>
This is my object in firestore:
usuarios / usuario: {
tabVisibleCatalogo: this.switch1,
}
If you are looking to retrieve data from your Firestore collection, I would suggest to implement a mounted (or created method) on your vue.js script. This article provides steps on getting data from Firestore from the two commonly used methods: mounted & asyncData. I would recommend you look into this article as you may find some correlations between those examples and what you are currently working on.
I managed to find similar posts that you may find relevant for your particular inquiry. Have a look at (1) & (2)

Mongoose - populate return _id only instead of a Object [duplicate]

In Mongoose, I can use a query populate to populate additional fields after a query. I can also populate multiple paths, such as
Person.find({})
.populate('books movie', 'title pages director')
.exec()
However, this would generate a lookup on book gathering the fields for title, pages and director - and also a lookup on movie gathering the fields for title, pages and director as well. What I want is to get title and pages from books only, and director from movie. I could do something like this:
Person.find({})
.populate('books', 'title pages')
.populate('movie', 'director')
.exec()
which gives me the expected result and queries.
But is there any way to have the behavior of the second snippet using a similar "single line" syntax like the first snippet? The reason for that, is that I want to programmatically determine the arguments for the populate function and feed it in. I cannot do that for multiple populate calls.
After looking into the sourcecode of mongoose, I solved this with:
var populateQuery = [{path:'books', select:'title pages'}, {path:'movie', select:'director'}];
Person.find({})
.populate(populateQuery)
.execPopulate()
you can also do something like below:
{path:'user',select:['key1','key2']}
You achieve that by simply passing object or array of objects to populate() method.
const query = [
{
path:'books',
select:'title pages'
},
{
path:'movie',
select:'director'
}
];
const result = await Person.find().populate(query).lean();
Consider that lean() method is optional, it just returns raw json rather than mongoose object and makes code execution a little bit faster! Don't forget to make your function (callback) async!
This is how it's done based on the Mongoose JS documentation http://mongoosejs.com/docs/populate.html
Let's say you have a BookCollection schema which contains users and books
In order to perform a query and get all the BookCollections with its related users and books you would do this
models.BookCollection
.find({})
.populate('user')
.populate('books')
.lean()
.exec(function (err, bookcollection) {
if (err) return console.error(err);
try {
mongoose.connection.close();
res.render('viewbookcollection', { content: bookcollection});
} catch (e) {
console.log("errror getting bookcollection"+e);
}
//Your Schema must include path
let createdData =Person.create(dataYouWant)
await createdData.populate([{path:'books', select:'title pages'},{path:'movie', select:'director'}])

after using $and query, the results aren't render on DOM

I am building some little log reporting with meteor.
have a dead simple table, that should contain all the data that received from the external mongodb server.
the html:
<tbody>
{{#each impressions}}
<tr>
{{> impression}}
</tr>
{{/each}}
</tbody>
js :
Meteor.subscribe('impressions');
...
...
Template.logResults.helpers({
'impressions': function() {
var sTs = Router.current().params.fromTs;
var eTs = Router.current().params.toTs;
return Impressions.find({});
}
});
So far, so good. BUT, when I am changing the query to this one :
Impressions.find({
$and: [{
ts: {
$gte: sTs
}
}, {
ts: {
$lte: eTs
}
}]
});
The results aren't displayed on the HTML DOM,
I tried to debug that, and created a console.log of this exact query,
and surprisingly all the correct results return successfully to the console.
screenshot attached.
I am probably doing something wrong, maybe with publish/subscribe thing.
help someone?
Thanks.
P.S. I removed the insecure and auto-publish,
have this code on the server folder
Meteor.publish('impressions', function() {
return Impressions.find();
});
and this code on the main lib folder
Impressions = new Mongo.Collection("banners");
enter image description here
The router stores the parameters for the current route as strings (which makes sense because URLs are strings), so you need to explicitly convert the values to integers before querying the database. Give something like this a try:
var sTs = Number(Router.current().params.fromTs);
var eTs = Number(Router.current().params.toTs);
Notes:
parseInt or parseFloat may be a better choice depending on the nature of your input. See this question for more details.
You could do the type conversion in the router itself and pass the values in the data context to the helpers. See this section of the iron router guide.
I suspect it worked when you typed it into the console because you used numbers instead of strings. E.g. ts: {$gte: 123} instead of ts: {$gte: '123'}.

No updating collection in mongodb

I use 0.6.4. Don't work Collection.update(t.data._id, { $set: { name: e.currentTarget.value}}); Session.set("edit-" + t.data._id, false);.
I'd recommend using jQuery to extract the value: $(e.currentTarget).val(). Also, assuming the person template is rendered from an {{#each people}}, you could probably just do this._id, but it's hard to tell without seeing the templates.
People.update(this._id, { $set: { name: $(e.currentTarget).val()}});
I'd also suggest logging these values to the console before the update to make sure the callback is getting executed and that you are reading the right values.