I am trying to display some basic data within chartjs and nextjs. below there is the main code and some key notes to consider
Main code having the problem
import Chart from "chart.js/auto";
import { RefObject, Dispatch, SetStateAction } from "react";
import { PriceApi } from "../endpoints/price";
import { FundingApi } from "../endpoints/market/Funding";
declare global {
interface HTMLCanvasElement {
chartInstance?: Chart;
}
}
export const makeChart = async (
ref: RefObject<HTMLCanvasElement>,
setRef: Dispatch<SetStateAction<RefObject<HTMLCanvasElement>>>,
asset: string,
timeframe: string,
days: string
) => {
try {
const [priceDataset, fundingDataset] = await Promise.all([
PriceApi(asset, timeframe, days),
FundingApi(asset, timeframe, days),
]);
const deploy = new Chart(ref.current, {
data: {
datasets: [priceDataset, fundingDataset],
},
options: {
scales: {
y: {
type: "linear",
},
"y-log": {
type: "logarithmic",
position: "left",
},
},
},
});
} catch (error) {
console.error("Error creating chart:", error);
}
};
Key notes
the useRef is actually a useState from react
const chartRef: RefObject<HTMLCanvasElement> =
useRef<HTMLCanvasElement>(null);
const [ref, setRef] = useState(chartRef);
the dataset returned within the funding and price api are an array for the chartjs new Chart componenet
const [priceDataset, fundingDataset] = await Promise.all([
PriceApi(asset, timeframe, days),
FundingApi(asset, timeframe, days),
]);
will return something like this =>
const dataset = {
type: "line",
label: "Price",
data: data,
borderWidth: 1,
fill: false,
yAxisID: "y-linear",
pointRadius: 0,
backgroundColor: "white",
borderColor: "white",
};
return dataset;
I am trying to create a const deploy = new Chart(ref, …) for then update it with useState: setRef(deploy)
also the chart seem to be loading but is strange. below I attach both error and image charts
[Error] Error creating chart: – Error: Canvas is already in use. Chart with ID '0' must be destroyed before the canvas with ID '' can be reused.
Error: Canvas is already in use. Chart with ID '0' must be destroyed before the canvas with ID '' can be reused.
(anonymous function) (app-index.js:33)
(anonymous function) (hydration-error-info.js:63)
(anonymous function) (chart.ts:46)
I actually tried with chatgpt but for some reason it just don’t work. it say to use .delete() and .destroy on the chart itself but I still get that error. I also had a look here with some guys having my similar problem but don’t seem to be working. I am using typescript
Efrem is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.