Next.js Discord

Discord Forum

Await dynamic import or some callback on complete?

Unanswered
Rojoss posted this in #help-forum
Open in Discord
Is there a way to trigger something when a dynamic import is completed?
I have a editor component that needs to be imported dynamically.
I also have other components on the page.
Now I want the page to display a loading bar while the editor is loading and not show any of the other components.

This is one approach I tried, but the promise of the import never resolves.
So the console log is never printed.
const MDXEditor = dynamic(() => import("./MDXEditor").then((mod) => {
    console.log('Editor loaded');
    resolveEditorLoaded();
    return mod;
}), {
    ssr: false,
    loading: () => <p>Loading...</p>
});

...

    const [isEditorLoaded, setIsEditorLoaded] = useState(false);

    useEffect(() => {
        const loadEditor = async () => {
            await editorLoadedPromise;
            setIsEditorLoaded(true);
        };
        loadEditor();
    }, []);


I also tried using <Suspense> to wrap the stuff on the page but it never renders the fallback content so that does not seem to work.

Lastly I tried awaiting another import but the timing is off.
So the import I'm awaiting completes before the dynamic import is loaded, which looks really bad.
    const [isEditorLoaded, setIsEditorLoaded] = useState(false);

    useEffect(() => {
        const loadEditor = async () => {
            await import("./MDXEditor");
            setIsEditorLoaded(true);
        };
        loadEditor();
    }, []);

2 Replies

Nobody?
can you share a min repro repo?