Home > Mobile >  Unhandled Rejection (TypeError): Cannot read properties of undefined (reading 'appendChild'
Unhandled Rejection (TypeError): Cannot read properties of undefined (reading 'appendChild'

Time:09-29

I am making a choropleth Map of AntV in React.js by using functional component. Here is my chart code:

import DataSet from '@antv/data-set';
import { Chart } from '@antv/g2';

const CustomerByRegion = () => {
   const [chartData , setChartData] = useState(null);

  useEffect(() => {
    
    getChartData()
      .then(data => {
        setChartData(data)
      })
  } ,[] );

 const getChartData = () => {
  return fetch("https://gw.alipayobjects.com/os/antvdemo/assets/data/world.geo.json").then(res => res.json())
  .then(mapData => {
    const chart = new Chart({
      container: 'container',
      autoFit: true,
      height: 500,
      padding: [55, 20]
    });
    chart.tooltip({
      showTitle: false,
      showMarkers: false,
      shared: true,
    });
    chart.scale({
      longitude: {
        sync: true
      },
      latitude: {
        sync: true
      }
    });
    chart.axis(false);
    chart.legend('trend', {
      position: 'left'
    });
    const ds = new DataSet();
    const worldMap = ds.createView('back')
      .source(mapData, {
        type: 'GeoJSON'
      });
    const worldMapView = chart.createView();
    worldMapView.data(worldMap.rows);
    worldMapView.tooltip(false);
    worldMapView.polygon().position('longitude*latitude').style({
      fill: '#fff',
      stroke: '#ccc',
      lineWidth: 1
    });
  });
 }
  
  return isLoading ? (
      <Spinner />
    ) : (
        <div id="container">
          {chartData}
        </div>
    );
};

export default CustomerByRegion;

Now this code is in .jsx file.

I am getting this error in " const chart = new Chart() ". Can anyone tell me the solution or guide me to the right path? Attached the error image.

enter image description here

CodePudding user response:

My guess would be that <div id="container"> hasn't mounted and rendered yet when you are exporting chartData from the other file. Do the fetch in a React lifecycle after the component has mounted and rendered.

Convert chartData into a function you can invoke from an useEffect hook when the CustomerByRegion mounts. You'll want to also ensure the id="container" div is mounted when the effect is running so it's identifiable.

export const getChartData = () => {
  return fetch(.....)
    .then(.....)
};

CustomerByRegion

import { useEffect, useState } from 'react';
import { getChartData } from "./chart";

const CustomerByRegion = () => {
  const [isLoading, setIsLoading] = useState(false);
  const [chartData, setChartData] = useState();

  useEffect(() => {
    setIsLoading(true);
    getChartData()
      .then(data => setChartData(data))
      .finally(() => setIsLoading(false));
  }, []);
  
  return (
    <div id="container">
      {isLoading ? <Spinner /> : chartData}
    </div>
  );
};
  • Related