Search code examples
reactjstypescriptbackoffice

Button does not appear without pressing F5


I'm currently having problems with my code. When I'm logged in as admin, my backoffice button doesn't appear unless I press F5.

useEffect(() => {
    // Make sure window.FB and window.FB.XFBML are defined before calling parse()
    if (window.FB && window.FB.XFBML) {
      window.FB.XFBML.parse();
    } else {
      console.log('Button BackOffice not loaded');
    }
  }, [])

How can I make my button appear immediately after logging in?


Solution

  • You should wait for the FB SDK to complete the login. You can subscribe to Events to wait until is ready. You are going to need something like this:

    useEffect(() => {
      // Function to handle the Facebook login event
      const handleFBLogin = (response) => {
        if (window.FB && window.FB.XFBML) {
          window.FB.XFBML.parse();
        } else {
          console.log('Button BackOffice not loaded');
        }
      };
    
      // Subscribe to the Facebook login event
      if (window.FB) {
        window.FB.Event.subscribe('auth.login', handleFBLogin);
      } else {
        console.log('Facebook SDK not loaded');
      }
    
      // Clean up the event subscription on component unmount
      return () => {
        if (window.FB) {
          window.FB.Event.unsubscribe('auth.login', handleFBLogin);
        }
      };
    }, []);