Hi!
I'm using Telegram's SDK for my webapp and in it's internal it's trying to access window object, which may be not initialized, so it throws an error ReferenceError: window is not defined.
I've tried putting 'use client' and 'client only' in affected files, but doesn't seem to change anything.
Everything is run on local machine with npm run dev (next dev).
I thought maybe I'll just catch this error and deal with it but I still get the error anytime I refresh the page.
So my question is, what is the correct way of handling such issue?
// ./app/page.tsx
'use client'
import { Suspense, useEffect } from "react";
import Main from "@/components/sections/main";
import TWA from "../lib/telegram";
export default function Home() {
useEffect(() => TWA?.ready);
return (
<Main>
<Suspense fallback={<p>Loading...</p>}>
<h1 className="text-3xl font-bold underline">Hello world!</h1>
</Suspense>
</Main>
);
};
// ./lib/telegram
'use client'
import WebApp from "@twa-dev/sdk";
const windowNotDefinedCatcher = (fn: Function) => {
try {
return fn()
} catch (error) {
console.log("Error: " + error)
if (error instanceof Error) {
if (error.message.includes("window is not defined")) {
console.warn("Telegram WebApp: window is not defined!")
} else {
console.error(error)
// throw error
}
}
}
}
const version = () => windowNotDefinedCatcher(() => WebApp.version)
const ready = () => {
windowNotDefinedCatcher(() => {
WebApp.ready();
console.debug("WebApp version: " + version());
})
}
const TWA = (() => {
return {
version: version,
ready: ready,
}
})();
export default TWA;