Skip to content

Instantly share code, notes, and snippets.

@klawingco
Created January 22, 2021 01:51
Show Gist options
  • Select an option

  • Save klawingco/5908293584ce8fd35ade87c9351c3e9a to your computer and use it in GitHub Desktop.

Select an option

Save klawingco/5908293584ce8fd35ade87c9351c3e9a to your computer and use it in GitHub Desktop.
useFacebook - a hook for Loading FB Login SDK for React
import { useState, useEffect, useCallback } from 'react';
const initializeFb = () =>
// eslint-disable-next-line no-unused-vars
new Promise((resolve, _reject) => {
if (typeof FB !== 'undefined') {
resolve();
} else {
// eslint-disable-next-line func-names
window.fbAsyncInit = function() {
// eslint-disable-next-line no-undef
FB.init({
appId: 'APP ID HERE',
cookie: true,
xfbml: true,
version: 'v2.8',
});
// eslint-disable-next-line no-undef
FB.AppEvents.logPageView();
resolve();
};
// eslint-disable-next-line func-names
(function(d, s, id) {
let js;
const fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) {
return;
}
// eslint-disable-next-line prefer-const
js = d.createElement(s);
js.id = id;
js.src = 'https://connect.facebook.net/en_US/sdk.js';
fjs.parentNode.insertBefore(js, fjs);
})(document, 'script', 'facebook-jssdk');
}
});
const useFacebook = () => {
const [fb, setFB] = useState([]);
const [isReady, setReady] = useState(false);
const initFacebook = useCallback(async () => {
await initializeFb();
// eslint-disable-next-line no-undef
if (typeof FB !== 'undefined') {
// eslint-disable-next-line no-undef
setFB(FB);
setReady(true);
}
});
useEffect(() => {
initFacebook();
}, [initFacebook]);
return [fb, isReady];
};
export default useFacebook;
@klawingco
Copy link
Author

usage

const Login= ()=>{
    const [FBInstance, isReady] = useFacebook();
    return (<Button onClick()=>{
      FBInstance.getLoginStatus(resp=>{  console.log(resp) })
   }></Button>)

}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment