tawk / tawk-messenger-react

Official React plugin for Tawk messenger
https://www.tawk.to
Other
23 stars 15 forks source link

Translation load issue #33

Open akram-hossan opened 8 months ago

akram-hossan commented 8 months ago

I have two widgetsId. One is for English and the other is for Spanish. So when I switch language from English to Spanish I have to reload twice and then the Spanish widget loads. But when I switch from Spanish to English It takes only one reload to load the English widget in the browser.

here is the code.

const TawkComponent: React.FC<ITawkComponent> = ({ authUser, lang }) => {
  const tawkMessengerRef = useRef<any>();
  const hash = CryptoJS.HmacSHA256('hello XYZ', '1g****3ld');
  const hashInBase64 = CryptoJS.enc.Base64.stringify(hash);

  const onChatMaximized = useCallback(() => {
    tawkMessengerRef.current.setAttributes(
      {
        userId: localStorage.getItem('userId'),
      },
      function (error: any) {
        console.log(error);
      }
    );

    tawkMessengerRef.current.setAttributes(
      {
        name: localStorage.getItem('userName'),
      },
      function (error: any) {
        console.log(error);
      }
    );

    tawkMessengerRef.current.setAttributes(
      {
        email: localStorage.getItem('userEmail'),
      },
      function (error: any) {
        console.log(error);
      }
    );

    tawkMessengerRef.current.setAttributes(
      {
        hash: hashInBase64,
      },
      function (error: any) {
        console.log(error);
      }
    );
  }, []);

  useEffect(() => {
    // Dynamically create and append the Tawk script
    const script = document.createElement('script');
    script.async = true;
    script.charset = 'UTF-8';
    script.setAttribute('crossorigin', '*');

    const widgetId = lang === 'en' || lang === 'de' ? '1g*****ld' : '1g****ccu';
    script.src = `https://embed.tawk.to/633605c554****12d8979f6c/${widgetId}`;

    script.onload = () => {
      window.Tawk_API = window.Tawk_API || {};
      window.Tawk_API.onLoad = () => {
        // Additional logic on Tawk load if needed
      };
    };

    document.head.appendChild(script);

    // Clean up the script tag when the component unmounts
    return () => {
      document.head.removeChild(script);
    };
  }, [lang]);

  return (
    <>
      {authUser ? (
        <TawkMessengerReact
          propertyId='633605c554****12d8979f6c'
          widgetId='1g****3ld'
          ref={tawkMessengerRef}
          onChatMaximized={onChatMaximized}
        />
      ) : (
        <TawkMessengerReact
          propertyId='633605c554****12d8979f6c'
          widgetId='1g****3ld'
          ref={tawkMessengerRef}
        />
      )}
    </>
  );
};

Why does it take two times to reload to the Spanish widget ? How can I fix this?

jaoaustero commented 1 week ago

Hi @akram-hossan there will be new API #4 will follow up for review and approval