How to fix 'ReferenceError: document is not defined' when using ZEGOCLOUD API with Next.js?

huangapple go评论66阅读模式
英文:

How to fix 'ReferenceError: document is not defined' when using ZEGOCLOUD API with Next.js?

问题

I can provide a translation of the code part for you:

我正在为在线视频会议制作一个网络平台我正在使用 ZEGOCLOUD 作为 API使用 Next.js但是当我运行我的程序时我收到了这个错误:#ReferenceError: document is not defined

import React, { useEffect, useState } from 'react';
import { useRouter } from 'next/router';
import { useDispatch, useSelector } from 'react-redux';
import { AppDispatch, RootState } from '@/configuration/store/store';
import { interview_interface, UserType } from '@/interface';
import useAuthInterview from '@/configuration/hooks/useAuthInterview';
import { GetInterview } from '@/configuration/slices/interview';
import { ZegoUIKitPrebuilt } from '@zegocloud/zego-uikit-prebuilt';
import { generatedMeetingID } from '@/functions/generatedMeetingID';

const Index = () => {
    useAuthInterview();
    const dispatch = useDispatch<AppDispatch>();
    const router = useRouter();
    const params = router.query.interviewid;
    const user = useSelector((state: RootState) => state.interviewUser.userInfo);
    const [isAllow, setIsAllow] = useState<boolean>(true);
    const [userLoaded, setUserLoaded] = useState(true);
    const interviews = useSelector((state: RootState) => state.interview.interviews);
    useAuthInterview();
    const users = useSelector((state: RootState) => state.interviewUser.userInfo?.uid);
    useEffect(() => {
        // @ts-ignore
        if (users?.uid) {
            dispatch(GetInterview());
        }
        setUserLoaded(true);
        // @ts-ignore
        const getMeeting = () => {
            if (params?.length && userLoaded) {
                const interviewData = interviews.filter((item: interview_interface) => item.idinterview === params);
                if (interviewData.length) {
                    const iscreator = users;
                    if (interviewData[0].interviewtype === '1-on-1') {
                        // compare avec l'id del 'inviter
                        if (interviewData[0].iduser) {
                            // compare avec la date d'aujourd'hui moment().format('l')
                            if (interviewData[0].interviewdate) {
                                setIsAllow(true);
                            }
                        } else {
                            router.push('/entreprise/interview');
                        }
                    }
                } else {
                    router.push('./appels');
                }
            }
        };
        getMeeting();
    }, [dispatch, userLoaded]);

    const appId = process.env.NEXT_PUBLIC_APPID;
    const serverSecret = process.env.NEXT_PUBLIC_SERVERSECRETE;
    const monInterview = async (element: any) => {
        // @ts-ignore
        const kitToken = ZegoUIKitPrebuilt.generateKitTokenForTest(
            // @ts-ignore
            appId,
            serverSecret,
            interviews[0].idinterview as string,
            // @ts-ignore
            users?.uid ? user : generatedMeetingID(),
            // @ts-ignore
            user.name ? user.name : generatedMeetingID()
        );
        // @ts-ignore
        const zp = await ZegoUIKitPrebuilt.create(kitToken);
        // @ts-ignore
        await zp.joinRoom({
            container: element,
            maxUsers: 50,
            sharedLinks: [{
                name: 'lien personnel',
                url: window.location.origin
            }],
            scenario: {
                mode: ZegoUIKitPrebuilt.VideoConference,
            }
        });
    };
    // @ts-ignore
    return (
        <div>
            <div ref={monInterview}>
            </div>
        </div>
    );
};

export default Index;

Please note that code translation might not cover all aspects, and you might need to adjust some parts depending on your specific requirements and environment.

英文:

I'm working on a web platform for online video conferencing and I'm using ZEGOCLOUD as api with next js but when I run my program I get this error #ReferenceError: document is not defined

import React, {useEffect, useState} from &#39;react&#39;;
import {useRouter} from &quot;next/router&quot;;
import {useDispatch, useSelector} from &quot;react-redux&quot;;
import {AppDispatch, RootState} from &quot;@/configuration/store/store&quot;;
import {interview_interface, UserType} from &quot;@/interface&quot;;
import useAuthInterview from &quot;@/configuration/hooks/useAuthInterview&quot;;
import {GetInterview} from &quot;@/configuration/slices/interview&quot;;
import {ZegoUIKitPrebuilt} from &quot;@zegocloud/zego-uikit-prebuilt&quot;;
import {generatedMeetingID} from &quot;@/functions/generatedMeetingID&quot;;
const Index = () =&gt; {
useAuthInterview()
const dispatch = useDispatch&lt;AppDispatch&gt;();
const router=useRouter()
const params=router.query.interviewid
const user=useSelector((state: RootState) =&gt; state.interviewUser.userInfo)
const [isAllow,setIsAllow]=useState&lt;boolean&gt;(true);
const [userLoaded,setUserLoaded]=useState(true)
const interviews = useSelector((state: RootState) =&gt; state.interview.interviews);
useAuthInterview()
const users = useSelector((state: RootState) =&gt; state.interviewUser.userInfo?.uid);
useEffect(() =&gt; {
// @ts-ignore
if (users?.uid) {
dispatch(GetInterview())
}
setUserLoaded(true)
// @ts-ignore
const getMeeting=()=&gt;{
if ((params?.length &amp;&amp; userLoaded)) {
const interviewData = interviews.filter((item: interview_interface) =&gt; item.idinterview === params)
if (interviewData.length){
const iscreator=users
if (interviewData[0].interviewtype===&#39;1-on-1&#39;){
// compare avec l&#39;id del &#39;inviter
if (interviewData[0].iduser){
// compare avec la date d&#39;aujourdhui moment().format(&#39;l&#39;)
if (interviewData[0].interviewdate){
setIsAllow(true)
}
}else{
router.push(&#39;/entreprise/interview&#39;)
}
}
}
else{
router.push(&#39;./appels&#39;)
}
}
}
getMeeting()
}, [dispatch,userLoaded])
const appId = process.env.NEXT_PUBLIC_APPID
const serverSecret = process.env.NEXT_PUBLIC_SERVERSECRETE
const monInterview=async (element:any)=&gt;{
// @ts-ignore
const kitToken=ZegoUIKitPrebuilt.generateKitTokenForTest(
// @ts-ignore
appId,
serverSecret,
interviews[0].idinterview as string,
// @ts-ignore
users?.uid? user:generatedMeetingID(),
// @ts-ignore
user.name?user.name:generatedMeetingID()
);
// @ts-ignore
const zp=await ZegoUIKitPrebuilt.create(kitToken)
// @ts-ignore
await zp.joinRoom({
container: element,
maxUsers: 50,
sharedLinks: [{
name: &quot;lien personnel&quot;,
url: window.location.origin
}],
scenario: {
mode: ZegoUIKitPrebuilt.VideoConference,
}
})
}
// @ts-ignore
return (
&lt;div&gt;
&lt;div ref={monInterview}&gt;
&lt;/div&gt;
&lt;/div&gt;
);
};
export default Index;

I tried deleting everything and starting again but it didn't work, but I also tested typeof window without success.

答案1

得分: 0

Next.js 是服务器端框架,因此文档不可用于服务器端。
你可以像这样导入。

import { useEffect } from "react";

export default function YourComponent() {
   useEffect(() => {
     import("zego-express-engine-webrtc").then(({ ZegoExpressEngine }) => {
     // 使用 ZegoExpressEngine 的代码
     });
    }, []);

   // 组件的其余部分代码
}
英文:

Nextjs is server side framework so document is not available on server side.
You can import like this.

import { useEffect } from &quot;react&quot;;
export default function YourComponent() {
useEffect(() =&gt; {
import(&quot;zego-express-engine-webrtc&quot;).then(({ ZegoExpressEngine }) =&gt; {
// Your code that uses ZegoExpressEngine
});
}, []);
// Rest of your component code
}

答案2

得分: 0

感谢您的回答,它确实对我有帮助,但我只是解构了导入。

const { ZegoUIKitPrebuilt } = await import("@zegocloud/zego-uikit-prebuilt");
英文:

Thanks for your answer, it really helped me, but instead of useEffect I just destructured the import.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

 const {ZegoUIKitPrebuilt} = await import(&quot;@zegocloud/zego-uikit-prebuilt&quot;);

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年5月29日 16:36:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/76355812.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定