tradingview / charting-library-tutorial

This tutorial explains step by step how to connect your data to the Charting Library
MIT License
397 stars 306 forks source link

NextJS Example/Tutorial - window not defined error #73

Open 0xAskar opened 1 year ago

0xAskar commented 1 year ago

Is there any tutorial or example that explains how to work with this library in Nextjs? I keep getting window is not defined error coming from the .standalone file. Not sure how to define window despite being in client side especially when the error is coming from the charting_library.standalone file.

The error occurs at the import TradingView from "../../chart/charting_library_clonned_data/charting_library/charting_library.standalone"; line and it then says window isn't defined.

import React, { useEffect, useLayoutEffect } from "react";
import Datafeed from "./datafeed";
import TradingView from "../../chart/charting_library_clonned_data/charting_library/charting_library.standalone";
export default function TradingViewChart (props) {
    const isOn = typeof window !== "undefined"
    const [chart, setChart] = useState(null)
  useEffect(() => {
    if (isOn) {
        const script = document.createElement("script");
        script.type = "text/jsx";
        script.src = "%PUBLIC_URL%/charting_library/charting_library.js";
        document.head.appendChild(script);

        window.tvWidget = new TradingView.widget({
        symbol: "Bitfinex:BTC/USD", // default symbol
        interval: "1D", // default interval
        fullscreen: true, // displays the chart in the fullscreen mode
        container: "tv_chart_container",
        datafeed: Datafeed,
        library_path: "/charting_library/",
        });
        //Do not forget to remove the script on unmounting the component!
        return () => script.remove();
    }
  }, []); //eslint-disable-line

  return <div id="tv_chart_container"></div>;
};
dexter4life commented 1 year ago

The reason for the "ReferenceError: window is not defined" error message is that the code is attempting to access the window object, which is only available in web browsers but not in Node.js. The window object is a global object in web browsers that provides access to the browser's window and DOM APIs.

The charting_library.standalone.js module you are attempting to import is intended to be used in a web browser, and it assumes that the window object is available. However, when you try to run this module in Node.js using the import statement, you are executing it in a non-browser environment where the window object is not defined, resulting in the error message.

So I suggest you move it to a different place, maybe where you think is best for you and make reference to it.