0

I am getting this warning when i try to render my chart with two datasets. (just a warning it renders fine)

[react-chartjs-2] Warning: Each dataset needs a unique key. By default, the "label" property on each dataset is used. Alternatively, you may provide a "datasetKeyProvider" as a prop that returns a unique key.

I see it says it tries to use label as a key but since i am putting a variable in there it is not guaranteed to be unique. I saw some solutions where people used Math.random() as a prop passed into the component but when i do this it removes one of my datasets. Is there a best practice on how to remove this warning?

Thanks!

const data = {
    labels: [
      "1MO",
      "3MO",
    ],
    datasets: [
      {
        label: props.chartItems?.[0]["create_date"],
        data: [
          props.chartItems?.[0]["one_month"],
          props.chartItems?.[0]["three_month"],
        ],
        backgroundColor: "red",
        borderColor: "red",
        fill: false,
        lineTension: 0,
        radius: 8,
      },
      {
        label: props.chartItems?.[1]["create_date"],
        data: [
          props.chartItems?.[1]["one_month"],
          props.chartItems?.[1]["three_month"],
        ],
        backgroundColor: "green",
        borderColor: "lightgreen",
        fill: false,
        lineTension: 0,
        radius: 4,
      },
    ],
  };

  return (
    <React.Fragment>
      <Line data={data} />
    </React.Fragment>
  );
bmccormick
  • 75
  • 1
  • 8

1 Answers1

3

You can use datasetKeyProvider which returns random id for the each datasets. Here is one example how to use it and function which creates random string using btoa.

 const datasetKeyProvider=()=>{ 
     return btoa(Math.random()).substring(0,12)
 } 

  return (
    <React.Fragment>
      <Line 
          data={data} 
          datasetKeyProvider={datasetKeyProvider}
      />
    </React.Fragment>
  );
Juha Kangas
  • 728
  • 5
  • 8
  • I may have overlooked something; i could have swore i tried this and it didn't work. But seems to be working fine now. Thanks! – bmccormick Nov 06 '20 at 21:21