How to keep waiting Vue until getting data from firebase? - firebase

I have a project that showing posts from a firebase realtime database. I use Vue, Vue-Router and Firebase Authentication. Firstly, when a user open the website, user see a login screen. In that screen page loads the posts from my database. Then when user login he/she routing to my Home.vue page. In here posts are showing there is no problem. But when user refresh the page, elements that are in the Home.vue are loading faster than my firebase data. I want to fix it.
That is my function that loads late from another javascript file:
function getData(data) {
var posts = data.val();
var keys = Object.keys(posts);
for(var i = 0; i < keys.length; i++) {
var id = keys[i];
var user = posts[id].user;
var text = posts[id].text;
var date = posts[id].date;
userPosts.push({
id: id,
user: user,
text: text,
date: date
});
}
userPosts.reverse();
}
export var userPosts = [ ];

You gotta look for lifecycle hooks in vue.js and use the one hook that triggers before/when the page is (re)loaded.. In it you set a Promise with your firebase function, that triggers getData() when resolved and go through with the chosen lifecycle hook.

Related

Nuxt3: Refresh useFetch data on page navigation

I have a comment component that fetches data using useFetch and user can sort the comments by time, likes, etc. Works good, However, the problem is that when user navigates to another post page with this comment component, the comments are not refreshed and thus the old commments from the previous blog page is still shown.
How do I refresh the data on new pages?
Here's my code:
const selectedSort = ref('newest')
const { data, pending, error, refresh } = useFetch(
`/api/comments/${selectedSort.value}/${route.params.id}`
)
I tried to add:
watch(
() => route.params.id,
async (newId) => {
refresh()
)
but that did not work...

Updating data that is passed into child component Angular2

I am new to development in Angular2 - Meteor. I have stumbled upon a problem while working with parent-child components. In the parent component, I have meteor subscribing to a collection.
users: any;
constructor(private _zone:NgZone){
var sub = Meteor.subscribe("accounts/users");
Tracker.autorun(function() {
_zone.run(function() {
if(sub.ready()){
this.users = Meteor.users.find().fetch();
console.log(this.users);
}
});
});
}
The user collection has 90 users in total. When the app initially loads, only the current user is found, thus the console log shows one user.
I am not sure if my placement of Tracker.autorun() and NgZone are correct, but after a second of the app loading, the console log shows an array of all 90 users. I assume this happens because the subscribe is not ready at first.
My child component takes in the fetched users as a parameter like this <sd-table [data]="users"></sd-table>. Upon loading of the application, there is only one user that is seen on the drawn template of the child component. Is there any way that the template can be updated when the subscribe happens and all users become accessible?
If you want to refer to this of the current class, don't use function()
users: any;
constructor(private _zone:NgZone){
var sub = Meteor.subscribe("accounts/users");
Tracker.autorun(() => {
_zone.run(() => {
if(sub.ready()){
this.users = Meteor.users.find().fetch();
console.log(this.users);
}
});
});
}
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/Arrow_functions

Why do Google's JS Client SDK function callbacks fail?

I'm currently in the learning phase for how the Google JS Client SDK works, since my boss needs me to learn how to integrate a Sign In button to his site to enable people to Authenticate via Google. I am testing the code for the custom Sign In button, with a touch of added functionality (like a Sign Out button), and in the process I've practically copy/pasted the code from their website. Let me show you the code first and then explain the issue, so that you can understand where the code is failing:
<script src="https://apis.google.com/js/client.js?onload=init"></script>
<script type="text/javascript">
var clientId = '{my client id here}'; // for web
var apiKey = '{my api key here}';
var scopes = 'profile email';
function SignOut() {
// I know, sloppy, but the signOut method from Google doesn't work.
window.location = 'https://accounts.google.com/logout';
// Additional code if necessary.
};
function makeApiCall() {
gapi.client.load('plus', 'v1', function () {
var request = gapi.client.plus.people.get({ 'userId': 'me' });
request.execute(function (response) {
var heading = document.createElement('h4');
var image = document.createElement('img');
image.src = response.image.url;
heading.appendChild(image);
heading.appendChild(document.createTextNode(response.displayName));
document.getElementById('name').appendChild(heading);
alert('User logged in. makeApiCall() has executed.');
})
})
};
function init() {
gapi.client.setApiKey(this.apiKey);
window.setTimeout(checkAuth, 1);
console.log('Up and ready to go.');
};
function checkAuth() {
// Triggers when the page and the SDK loads.
gapi.auth.authorize({ client_id: clientId, scope: scopes, immediate: true }, handleAuthResult);
};
function handleAuthClick(event) {
// Triggers after a user click event to ensure no popup blockers interfere.
gapi.auth.authorize({ client_id: clientId, scope: scopes, immediate: false }, handleAuthResult);
return false;
};
function handleAuthResult(authResult) {
var authorizeButton = document.getElementById('SignInBtn');
var signoutButton = document.getElementById('SignOutBtn');
if (authResult && !authResult.error) {
var V = JSON.stringify(authResult);
localStorage.setItem('GoogleAuthResult', V);
console.log(V); // Just for testing...
var authTimeout = (authResult.expires_in - 5 * 60) * 1000; setTimeout(checkAuth, authTimeout); // As recommended by a Google employee in a video, so that the token refreshes.
authorizeButton.style.display = 'none'; // Switching between Sign In and Out buttons.
signoutButton.style.display = 'inline-block';
makeApiCall();
} else {
// Immediate:true failed so user is NOT signed in.
// Make the Sign In button the one visible and prep it
// so that it executes the Immediate:false after user click:
authorizeButton.style.visibility = 'inline-block';
authorizeButton.onclick = handleAuthClick;
signoutButton.style.visibility = 'none';
}
};
</script>
The handleAuthClick function does run on the button click, but after taking the user to the Google Sign In page, when that page brings me back, the browser kinda flickers and the handleAuthResult function does not execute. Therefore, nothing changes in the page after the successful sign in; the button displayed is the Sign In button (Sign Out button not visible) and no information is displayed on the 'name' textNode. This happens on Internet Explorer (11), Firefox (39) and Chrome (44). Also, it happens at home on my laptop (straight connection to the web via Cable broadband) and at work (on Windows 8.1 behind an Active Directory).
I began wondering so I started refreshing the browser page and after a couple of refreshes, since the script runs from the beginning, the immediate:true fires again and voilá: user is connected and API call triggers.
So, on my laptop, I changed the function being called back, in the immediate:false line's callback parameter, to the init() function and that fixed the problem: everything runs smoothly from beginning to end. Yet, this is not the way it is supposed to work. I still don't know what is going on with that line.
This morning, on my computer at work (behind Active Directory), that fix didn't work. I have to refresh the page a couple of times so that the script runs from the beginning and the immediate:true triggers recognizing the user's Signed In state and displaying the proper button on screen.
Any ideas on why does this callback fail?
You need to define your apiKey in the first section of your code
var clientId = '{my client id here}'; // for web
var apiKey = '{my api key here}'
Maybe thats the problem.
Google ApiKeys

Adding Firebase VAR to website

I setup and account at http://feedthefire.in and on Firebase dot com - to manage feeds I would liek to display on my site. I set everything up and the feeds get pulled into Firebase just like it should, now its time to add it to a web page...nothing, can't get the feeds to pull in from Firebase. I added the firebase.js reference in the header and in the body I placed
<script type="text/javascript">
var ref = new Firebase"'https://aodf.firebaseio.com");
ref.child("meta").once("value", function(snapshot) {
$("#e-title").html(snapshot.val().description);
});
ref.child("articles").limit(3).on("child_added", function(snapshot) {
var article = snapshot.val();
var link = $("<a>", {
"href": article.link,
"target": "_blank"
});
$("#e-list").append($("<li>").append(link.html(article.title)));
});
when you go to http://sandbox.studiorooster.com/ao I should see a list of feeds, but I don't, so I know I am supposed to place something else in the code; I think :)
There are a number of problems in what you posted above, each of which is explained below:
Syntax error on line #2: var ref = new Firebase("https://aodf.firebaseio.com");
You're loading a description on lines #3-5, but never rendering it, because there is no element with id e-title in the page you linked to. Trying adding <h2 id="e-title"></h2> to your template.
Similarly, you are loading a number of articles on lines #6-13, and trying to append each of these items to a list with id e-list, which also does not exist in your template. Try adding <ul id="e-list"></ul> to your template.
Hope that helps!

Facebook Fan Page Id in associated Facebook App

I am developing a facebook application which required to get below information while load.
Facebook Fan Page URL / Id on which the application has been added.
If the user who is accessing this application from specific page is admin of that page or not.
I am developing this application in ASP.Net and I am using Facebook Graph API.
Any help is highly appreciated.
Let me share some insights
Firstly, I would strongly suggest that you use Microsoft's Facebook C# SDK instead of using plain calls in your .NET project.
Steps
With the current API, you can do this in your ADMIN Page
Ask the user to connect and ask for manage pages permission (manage_page)
with the permisions to manage the pages, you can easily fill up a dropdown with all pages that the user have
Ask the user to add your app to it's own page as a tab using http://facebook.com/add.php?api_key=[API_KEY]&pages=1&page=[PAGE_ID]
Now that you have your app running on the user page, you need a way to check if that page is running inside Facebook as a Tab or not, and what's the Page Id that is running from.
In your App Tab Url page that you specified, ask for the signed_request and verify the Data as it has the ["page"]["id"] that you need so you can check against the saves Page_Id that you should have saved on the ADMIN area when your user adds your app to it's facebook page.
I hope this helps.
Code
To login and request all user pages:
<select class="facebook-page-list" disabled="disabled">
<option>Facebook pages</option></select>
<script>
<!--
FB.init({
appId: 'API_KEY',
cookie: true,
status: true,
xfbml: true
});
FB.api('/me', function (user) {
if (user != null) {
if (user.error) {
$(".fb-login").show();
} else {
// example from Facebook
var image = document.getElementById('image');
image.src = 'https://graph.facebook.com/' + user.id + '/picture';
var name = document.getElementById('name');
name.innerHTML = user.name
// get all user Pages
facebookGetPages();
}
}
});
function facebookGetPages() {
FB.getLoginStatus(function (response) {
if (response.session) {
access_token = response.session.access_token;
FB.api(
{
method: 'fql.multiquery',
access_token: access_token,
queries: {
query1: 'select page_id from page_admin where type <> "APPLICATION" and uid = ' + response.session.uid,
query2: 'select page_id, name, page_url from page where page_id in (select page_id from #query1)'
}
}, function (queries) {
if (queries.error_msg)
alert(queries.error_msg);
else {
pages = queries[1].fql_result_set;
$(".facebook-page-list").empty();
for (i = 0; i < pages.length; i++)
$(".facebook-page-list").append("<option value='" + pages[i].page_id + "'>" + pages[i].name + "</option>");
$(".facebook-page-list").attr("disabled", false);
}
});
} else {
// no user session available, someone you dont know
}
});
}
//-->
</script>
To get the Page ID from your app:
ViewBag.signed_request = "can't get id";
dynamic signed_request = FacebookWebContext.Current.SignedRequest;
if(signed_request != null)
{
ViewBag.signed_request = signed_request.Data.page.id;
}

Resources