Untitled

 avatar
unknown
typescript
4 years ago
2.4 kB
27
Indexable
import React, { PureComponent } from 'react';
import { createChart, IChartApi, ISeriesApi } from 'lightweight-charts';
import Papa from 'papaparse';
import { useSelector, useDispatch, connect } from 'react-redux';
import LineData from '../interfaces/LineData';
import { RootState } from '..';
import { setData } from '../redux/actions';

class MyChart extends PureComponent {
    csvData: any[] = [];
    chart: IChartApi | null = null;

    async componentDidMount() {
        const chart = createChart(document.body, { width: 800, height: 600 });
        this.chart = chart;

        const lineSeries = chart.addLineSeries();

        this.initLineSeries(chart, lineSeries);
    }

    componentWillUnmount() {
        if (this.chart !== null) {
            this.chart.remove();
            this.chart = null;
        }
    }

    initLineSeries(chart: IChartApi, lineSeries: ISeriesApi<"Line">) {
        //read csv
        Papa.parse("http://localhost:3000/data.csv", {
            download: true,
            complete: result => {
                var data: LineData[] = [];

                result.data.forEach(e => {
                    var row = e as string[];
                    var time: string = row[0];
                    var value: number = +row[1];
                    data.push({ time: time, value: value });
                });

                //nefunguje - radek 44 chyba: React Hook "useDispatch" is called in function "complete" that is neither a React function component nor a custom React Hook function. React component names must start with an uppercase letter  react-hooks/rules-of-hooks
                const dispatch = useDispatch();
                dispatch(setData);

                //nefunguje - radek 48 stejna chyba jako 44
                const storeData = useSelector((state: RootState) => state.chartData);
                lineSeries.setData(storeData);

                chart.timeScale().setVisibleRange({
                    from: data[0].time,
                    to: data[data.length - 1].time,
                });
            }
        });
    }

    render() {
        return (
            <div
                id='lightweight_chart_container'
                className={'LightweightChart'}
            />
        );
    }
}

export default MyChart;
Editor is loading...