0

Can someone please help me with this

  getFriendList () {

        let friends = null;

        FB.api('/me/taggable_friends',{
            fields: 'id,name,picture',
            limit: 10,
            access_token: this.state.fbResponse.authResponse.accessToken
        }, (response) => {
            friends = response.data.map(friend => {
                return(
                    <Friend key={friend.id} />
                );
            });
        }); 

        return friends;
  };

It is not returning the friends list. Always returns null. please help.

I'm getting 10 data. When I do console.log, It is printing.

Thanks in advance...

Govind Raj
  • 105
  • 6
  • https://stackoverflow.com/questions/6847697/how-to-return-value-from-an-asynchronous-callback-function – pawel Nov 07 '17 at 08:45

1 Answers1

4

FB.api is asynchronous and this is why you are getting null as result.

Can't you save friends in your state?

getFriendList () {
  FB.api('/me/taggable_friends',{
    fields: 'id,name,picture',
    limit: 10,
    access_token: this.state.fbResponse.authResponse.accessToken
  }, (response) => this.setState({ friends }))
}

I guess you are calling this method on componentDidMount:

componentDidMount() {
  this.getFriendsList()
} 

and later render friends list upon completion:

render() {
  return(
    <div>
      {this.state.friends && this.state.friends.map(friend =>
        <Friend key={friend.id} />
      )}
    </div>
  )
}
rrd
  • 5,789
  • 3
  • 28
  • 36
Hemerson Carlin
  • 7,354
  • 1
  • 27
  • 38
  • Thanks for your response. Previously I'm using this function in render function. So I cannot use setState. Now I changed with DidMount & working. – Govind Raj Nov 07 '17 at 08:44
  • `componentDidMount` is the [recommended](https://reactjs.org/docs/react-component.html#componentdidmount) place to fetch data from remote api as well described in ReactJS docs. Calling it on render is not a good practice though. – Hemerson Carlin Nov 07 '17 at 08:48