Home > Enterprise >  using 'window' in useEffect dependency - NextJS
using 'window' in useEffect dependency - NextJS

Time:10-01

I have a function which should run when window.performance.getEntriesByType("navigation")[0].type changes. I am trying to do this with useEffect, but I get the window is not defined reference error.How should I run the function on the change? Edit: The basic idea is that, that a player can create a room, and with the room id an another can join. But if the host leaves the page the room should be closed, or if the other player leaves the room the player should leave the room.

 useEffect(() => {
    interrupt()
  }, [window.performance.getEntriesByType("navigation")[0].type]);

async function interrupt(){

    if (players && currentRoom && window.performance.getEntriesByType("navigation")[0].type == 'reload') {
        const docRef = doc(db, "versus_ongoing", currentRoom)

        if(players.players[0].user == user.uid){
            deleteDoc(docRef)
        } else {
            await updateDoc(docRef, {
                players: players.players.filter(post => post.host == true)
            })
        }
      } else {
        console.info( "This page is not reloaded");
      }   
}

CodePudding user response:

I think that window is not available in NextJS until the mount is completed and since it references window in the deps array itself, its actually being consumed before that.

Using this in the deps array wont work anyway sadly, since effect dependencies can only be state or props -- or it wont trigger when it changes.

I don't know enough about your use case but I don't think window.performance.getEntriesByType("navigation")[0].type ever changes anyway? In which case, you simply don't need it in the deps array:

 useEffect(() => {
    interrupt()
  }, []);

CodePudding user response:

I would probably create a state variable, watch for that in the useEffect dependency, and set the state variable on the client side.

const [test, setTest] = useState();

if (typeof window !== "undefined") {
  setTest(window.performance.getEntriesByType("navigation")[0].type);
}

useEffect(() => {
   interrupt()
}, [test]);
  • Related