The Facebook Graph API code I am using to login users is calling my getfriends() loop function twice. How can I change the code so that the loop function is only called once, whilst still allowing users in various states to login?
<html xmlns:fb="https://www.facebook.com/2008/fbml">
<head>
<title>FB App</title>
<script>
var userList = [];
userCount = 0;
function getfriends () {
console.log("getFriends");
var url = "/me/friends";
FB.api(url, function (response) {
userList = userList.concat(response.data);
userCount = response.data.length;
compareAllFriends();
});
}
function compareAllFriends () {
console.log("compareAllFriends");
var i = 0, l = 10, userID;
for (; i < l; i += 1) {
userID = userList[i].id;
compareFriendsWith (i, userID);
}
}
function compareFriendsWith (i, id) {
console.log("compareFriendsWith", i, id);
}
</script>
</head>
<body>
<div id="fb-root"></div>
<p align="right"><button id="fb-auth">Login</button></p>
<script type="text/javascript">// <![CDATA[
window.fbAsyncInit = function() {
FB.init({ appId: 'APP_ID',
status: true,
cookie: true,
xfbml: true,
oauth: true});
function updateButton(response) {
var button = document.getElementById('fb-auth');
if (response.authResponse) {
//user is already logged in and connected
FB.api('/me', function(response) {
getfriends();
button.innerHTML = 'Logout';
});
button.onclick = function() {
FB.logout();
};
} else {
//user is not connected to your app or logged out
button.innerHTML = 'Login with Facebook';
button.onclick = function() {
FB.login(function(response) {
if (response.authResponse) {
FB.api('/me');
} else {
//user cancelled login or did not grant authorization
}
}, {scope:''});
}
}
}
// run once with current status and whenever the status changes
FB.getLoginStatus(updateButton);
FB.Event.subscribe('auth.statusChange', updateButton);
};
(function() {
var e = document.createElement('script'); e.async = true;
e.src = document.location.protocol
+ '//connect.facebook.net/en_US/all.js';
document.getElementById('fb-root').appendChild(e);
}());
// ]]></script>
</body>
</html>
It appears that the problem may be that
updateButton()is run more than once and that in turn callsgetfriends()more than once.Judging from the Facebook docs, since you set
status: trueininit(), you don’t need this line:That will happen automatically in the next line where you invoke
subscribe(). So that’s probably why you’re seeinggetfriends()executed twice.If that doesn’t work, a quick but much less elegant workaround might be to have a variable like
hasfriends, initialize it tofalse, check its value inside ofgetfriends(), and havegetfriends()do nothing if it’strue. If it’sfalse, set it totrueingetfriends()so the main code ingetfriends()only runs once.