benweet / stackedit.js

Add StackEdit to any website
https://benweet.github.io/stackedit.js/
MIT License
1.08k stars 119 forks source link

NextJS - getting window is not defined even after checking if window is undefined #44

Closed ivandimitrov8080 closed 1 year ago

ivandimitrov8080 commented 1 year ago

When I try to build I always get this:

- info Compiled successfully
- info Collecting page data ...ReferenceError: window is not defined
    at Object.<anonymous> (/home/ivand/work/hoi2/wiki/node_modules/.pnpm/stackedit-js@1.0.7/node_modules/stackedit-js/docs/lib/stackedit.js:103:14)
    at __webpack_require__ (/home/ivand/work/hoi2/wiki/node_modules/.pnpm/stackedit-js@1.0.7/node_modules/stackedit-js/docs/lib/stackedit.js:30:30)

This is the tsx:

import { useEffect, useState } from 'react';
import Stackedit from 'stackedit-js'
import ArticleType from '../interfaces/article';

type Props = {
    article: ArticleType;
};

const StackeditComponent = ({ article }: Props) => {
    const [markdown, setMarkdown] = useState(article?.markdown)
    const [title, setTitle] = useState(article?.title)

    useEffect(() => {
        if (typeof window !== "undefined") {
            const stackedit = new Stackedit() // This line throws the error
            stackedit.openFile({
                name: title || "",
                content: {
                    text: markdown || ""
                }
            })
            stackedit.on('fileChange', (file) => {
                setMarkdown(file.content.text);
                setTitle(file.name)
            });
        }
    }, [])

    return <textarea className="invisible" defaultValue={markdown} />
}

export default StackeditComponent

The constructor is causing problems, because when I comment it out it works.

ivandimitrov8080 commented 1 year ago

This is a NextJS specific problem - SSR.