[Chartjs]-React Charts – Display pie chart despite zero values (Equally distribute sections and display colorized chart when all the values are zero)

4👍

Conditionally rendering super small values resolved my issue.

  const bothZero = !data.remainingLimit && !data.usedLimit
  const conditionalData = bothZero
    ? [1e-10, 1e-10]
    : [data.remainingLimit, data.usedLimit];

  const chartData = React.useMemo(() => {
    return {
      labels: [t("label.remainingLimit"), t("label.usedLimit")],
      datasets: [
        {
          data: conditionalData,
          backgroundColor: [secondary, primary],
          hoverBackgroundColor: [secondary, primary],
          borderWidth: 4,
        },
      ],
    };
  }, [data]);
// Standardized solution for N values (Might be handy if the number of fields is not known ahead of time) - Assumes that data is object

const allZero = Object.values(data).every(value => isZero(value));

const conditionalData = allZero
  ? Array(Object.keys(data).length).fill(1e-10)
  : Object.values(data);

enter image description here

Leave a comment