Created
January 22, 2021 01:51
-
-
Save klawingco/5908293584ce8fd35ade87c9351c3e9a to your computer and use it in GitHub Desktop.
useFacebook - a hook for Loading FB Login SDK for React
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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; |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
usage