50
loading...
This website collects cookies to deliver better user experience
index.html
, but that's not something we want to do. We might not want to include the SDK on every page. Instead, it might be a good idea to build a wrapper for the SDK using React Hooks. This gives us access to all functionality provided by Facebook, while still keeping full control.const useFacebook = () => {
useEffect(() => {
const script = document.createElement("script");
script.async = true;
script.defer = true;
script.crossOrigin = "anonymous";
script.src = `https://connect.facebook.net/nl_BE/sdk.js`;
document.body.appendChild(script);
window.fbAsyncInit = function () {
FB.init({
appId: <ENTER YOUR FACEBOOK APP ID HERE>,
autoLogAppEvents: true,
xfbml: true,
version: "v11.0",
});
};
return () => {
delete window.fbAsyncInit;
document.body.removeChild(script);
};
}, []);
};
fbAsyncInit
property on window
, which doesn't have that property to begin with. We need to add this property to the Window interface by adding the following code:declare global {
interface Window {
fbAsyncInit?: Function;
}
}
FB
variable that gets inserted by the script. You can fix this by adding @types/facebook-js-sdk
to your project:npm install @types/facebook-js-sdk --save-dev
FB.login
function. By default, the FB.login
function returns a response, regardless of the result. Let's turn this into a promise that returns the response if the login is successful and throws an error otherwise:const login = () => {
return new Promise<fb.StatusResponse>((resolve, reject) => {
FB.login((response) => {
if (response.status === "connected") resolve(response);
else reject(new Error("Facebook login failed"));
});
});
};
fb.StatusResponse
comes from: it's a type used in TypeScript that comes from @types/facebook-js-sdk
.