1

How do I achieve the code below using Next.js.

I believe there is an issue with Next.js not being able to access the window object unless you're inside a useEffect(() => {}) hook.

Changing to regular React, this code worked fine.

What am I missing in the Next.js ecosystem that doesn't allow this type of delayed render to work?

Thank you.

import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
import reportWebVitals from "./reportWebVitals";
import { initializeContract } from "./utils/near";

window.nearInitPromise = initializeContract()
  .then(() => {
    ReactDOM.render(
      <React.StrictMode>
        <App />
      </React.StrictMode>,
      document.getElementById("root")
    );
  })
  .catch(console.error);

reportWebVitals();

Update: Here is my attempt with Next.js

import { useEffect } from "react";
import { initializeContract } from "../utils/near";

function MyApp({ Component, pageProps }) {
  useEffect(() => {
    window.nearInitPromise = initializeContract().then(() => renderApp());
  }, []);

  const renderApp = () => {
    return <Component {...pageProps} />;
  };
}

export default MyApp;
G087
  • 23
  • 3
  • Do you actually need to prevent the _whole app_ from rendering until that condition is met? Next.js pre-renders all pages on the server, so having a client-side condition that prevents rendering the whole app won't work. You could apply this to specific parts of the app/components, though. – juliomalves Apr 27 '22 at 21:58

1 Answers1

0

That's because window object is not available on server-side (nodejs), when you use it inside useHook it's executed client-side. (when the component is mounted).

So if you run your code inside an useEfect this ensures that your code only runs on the client-side.

Window is not defined in Next.js React app

waken22
  • 11
  • 1
  • Thank you for taking the time to reply. I've updated the code with how I believed it would work. I'm waiting for the promise to resolve, then rendering the app. I'm just left with a blank screen with no app loading. – G087 Apr 26 '22 at 09:32