How do I load Next.js App after promise is resolved?

Viewed 285

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;
1 Answers

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

Related