Using Chart.js library to draw a Line graph using coingeko api is not working properly

36 views Asked by At

I got below error when I try implement a line chart

Canvas is already in use. Chart with ID '0' must be destroyed before the canvas with ID '' can be reused.

The code below is used visually to represent the Historical/periodic chart of cryptocurrency over period of time

const CoinInfo = ({ coin }) => {
  const [historicData, setHistoricData] = useState();
  const [days, setDays] = useState(1);
  const { currency } = useCryptoState();
  let chartRef = null;
  Chart.register(CategoryScale);

  const fetchHistoricData = async () => {
    const { data } = await axios.get(HistoricalChart(coin.id, days, currency));
    setHistoricData(data?.prices);
  };

  console.log(coin);

  useEffect(() => {
    fetchHistoricData();
  }, [days]);

  useEffect(() => {
    if (chartRef) {
      chartRef.destroy();
    }
  }, []);

  const darkTheme = createTheme({
    palette: {
      primary: {
        main: "#fff",
      },
      type: "dark",
    },
  });

  const StyledContainer = styled("div")({
    width: "75%",
    display: "flex",
    flexDirection: "column",
    alignItems: "center",
    justifyContent: "center",
    marginTop: 25,
    padding: 40,
    [theme.breakpoints.down("md")]: {
      width: "100%",
      marginTop: 0,
      padding: 20,
      paddingTop: 0,
    },
  });

  const chartData = {
    labels: historicData?.map((coin) => {
      const date = new Date(coin[0]);
      const time =
        days === 1
          ? `${date.getHours()}:${date.getMinutes()}`
          : date.toLocaleDateString();
      return time;
    }),
    datasets: [
      {
        data: historicData?.map((coin) => coin[1]),
        label: `Price (Past ${days} Days) in ${currency}`,
        borderColor: "#EEBC1D",
      },
    ],
  };

  return (
    <ThemeProvider theme={darkTheme}>
      <StyledContainer>
        {!historicData ? (
          <CircularProgress
            style={{ color: "gold" }}
            size={250}
            thickness={1}
          />
        ) : (
          <>
            <Line
              ref={(reference) => (chartRef = reference)}
              data={chartData}
            />
          </>
        )}
      </StyledContainer>
    </ThemeProvider>
  );
};

export default CoinInfo;
0

There are 0 answers