HartleySan
HartleySan

Reputation: 7810

How do I paginate results from the Facebook SDK friends endpoint?

I'm using the Facebook SDK for JS to get a list of FB friends for a given FB user ID. Essentially, I make a request as follows:

FB.api(`/${fbUserId}/friends`, (response) => {
    if (response && response.data) {
        fbFriends = fbFriends.concat(response.data);
    }

    if (response && response.paging && response.paging.cursors && response.paging.cursors.after) {
        // Recurse through.
    }
});

I can get the first set of results, which contains 13 friends, and can also see that there are 200+ friends total, but the problem I'm having is when I try to recurse through and get all 200+ friends.

Specifically, I'm referencing the following two pages:

  1. https://developers.facebook.com/docs/graph-api/using-graph-api/#cursors
  2. https://developers.facebook.com/docs/graph-api/reference/user/friends/

Trying to put things together from those two pages, I thought that a request URL like the following would work:

const afterParam = response.paging.cursors.after ? `&after=${response.paging.cursors.after}` : '';

FB.api(`/${fbUserId}/friends${afterParam}`, (response) => {
...

But it doesn't return any results. I am console-logging response.paging.cursors.after, and I'm sure it's set appropriately from the first API call, but it's not returning any more friends. I always get back an empty array for response.data.

What am I doing wrong? Admittedly, the FB API docs seem a bit sparse, and I don't see anywhere where they specifically show how to go through pages of results for the friends API endpoint, but I'm obviously missing something. Thank you.

Upvotes: 1

Views: 749

Answers (0)

Related Questions